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
How to use Knockout's data-bind attribute in Mvc helpers like Html.EditorFor()
提问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 EditorFor
does 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
EditorFor
cannot add HTML attributes to the element. Use TextBoxFor
instead:
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 additionalViewData
like so:
将字段的名称(在本例中name
)传递给编辑器模板,作为其中的一部分,如下additionalViewData
所示:
@Html.EditorFor(t => t.name, "", new { fieldName = "name" })
Then in your editorTemplate
you 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.
希望这可以帮助某人。