Custom attribute with dash in name using EditorFor/TextBoxFor/TextBox helpers

孤街醉人 提交于 2019-12-10 00:50:18

问题


I am using Knockout-JS to bind properties in my view to my view model. Knockout-JS uses a custom attribute called 'data-bind' that you have to append to controls in which you want to be bound to view model objects.

Example:

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

Notice the 'data-bind' attribute.

In my view rendering, I am having trouble rendering a textbox that has this attribute. I am aware the Html.EditorFor, Html.TextBoxFor, and Html.TextBox helpers all take an anonymous object that you can use to specify custom attributes. The only problem with this implementation is C# doesn't allow dashes as variable names, so this won't compile: @Html.EditorFor(m => m.FirstName, new { data-bind = "value: firstName" });

The only thing I can think of is this (in view-model):

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

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

And a view template called "DataBindingInput.cshtml":

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

The only trouble with this is I lose the automatic generation of the input name so it won't work on a post-back because the model binder has no idea how to bind it.

How can I make this work?


回答1:


Thanks to Crescent Fish above, looks like you can just use underscores and MVC 3 will convert them to dashes since underscores aren't allowed in HTML attribute names.



来源:https://stackoverflow.com/questions/6525838/custom-attribute-with-dash-in-name-using-editorfor-textboxfor-textbox-helpers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!