javascript 如何在 Html.EditorFor() 等 Mvc 助手中使用 Knockout 的数据绑定属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16720732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 05:44:32  来源:igfitidea点击:

How to use Knockout's data-bind attribute in Mvc helpers like Html.EditorFor()

javascriptasp.net-mvcasp.net-mvc-4knockout.js

提问by Vlado Pand?i?

I tried this @Html.EditorFor(model => model.Name, " ", new { data_bind = "value:firstName" });and other possible overloades but none of them seem to work.

我尝试了这个 @Html.EditorFor(model => model.Name, " ", new { data_bind = "value:firstName" });和其他可能的重载,但它们似乎都不起作用。

The rest of code:

其余代码:

<script type="text/javascript">
$(document).ready(function () {

    function AppViewModel() {
        this.firstName = ko.observable("");
        this.lastName = ko.observable("");
    }
    ko.applyBindings(new AppViewModel());
});

回答by Matt Houser

Your 3rd parameter to EditorFordoes not do what you think it should be doing.

您的第三个参数 toEditorFor没有做您认为应该做的事情。

See http://msdn.microsoft.com/en-us/library/ff406461(v=vs.98).aspx

请参阅http://msdn.microsoft.com/en-us/library/ff406461(v=vs.98).aspx

EditorForcannot add HTML attributes to the element. Use TextBoxForinstead:

EditorFor无法向元素添加 HTML 属性。使用TextBoxFor来代替:

@Html.TextBoxFor(model => model.Name, new { data_bind = "value:firstName" });

回答by Justin Cale

I understand I'm a bit late on this one, but here's a solution I've been using.

我知道我在这个问题上有点晚了,但这是我一直在使用的解决方案。

Pass the name of the field (in this case name) to the editor template as part of the additionalViewDatalike so:

将字段的名称(在本例中name)传递给编辑器模板,作为其中的一部分,如下additionalViewData所示:

@Html.EditorFor(t => t.name, "", new { fieldName = "name" })

Then in your editorTemplateyou can have this:

然后在你的editorTemplate你可以有这个:

@{
    var fieldName = ViewData.Where(v => v.Key == "fieldName").FirstOrDefault().Value;
}
@Html.TextBox("", Model, new { data_bind = "value:"+fieldName })

Hope this helps someone.

希望这可以帮助某人。