asp.net-mvc-3 – 使用EditorFor/TextBoxFor/TextBox助手的名称中的破折号的自定义属性

我使用Knockout-JS来将我的视图中的属性绑定到我的视图模型。 Knockout-JS使用一个名为“data-bind”的自定义属性,您必须附加到要绑定到其中的控件来查看模型对象。

例:

<input type='text' name='first-name' data-bind='value: firstName'/>

注意’data-bind’属性

在我的视图渲染中,我无法呈现具有此属性的文本框。我知道Html.EditorFor,Html.TextBoxFor和Html.TextBox帮助器都使用一个可以用来指定自定义属性的匿名对象。这个实现的唯一问题是C#不允许破折号作为变量名,所以这不会编译:
@ Html.EditorFor(m => m.FirstName,new {data-bind =“value:firstName”});

我唯一可以想到的是(在视图模型中):

public class DataBindingInput
{
     public string Value { get; set; }
     public string DataBindingAttributes { get; set }
}

public class Myviewmodel
{
    ...
    public DataBindingValue firstName { get; set; }
    ....
}

一个名为“DataBindingInput.cshtml”的视图模板:

@model DataBindingInput
<input type='text' data-binding='@Model.DataBindingAttributes' value='@Model.Value'>

唯一的麻烦是我失去了自动生成的输入名称,因此它不会在后端工作,因为模型绑定器不知道如何绑定它。

我该怎么做这个工作?

解决方法

感谢上面的Crescent Fish,看起来你可以使用下划线,MVC 3将会将它们转换为破折号,因为HTML属性名称中不允许使用下划线。

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...