19

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?

Michael Brennan
  • 1,031
  • 8
  • 19
  • 8
    See http://stackoverflow.com/questions/2520487/how-to-use-html-5-data-attributes-in-asp-net-mvc/4515095#4515095 – Crescent Fresh Jun 29 '11 at 19:14
  • Thanks, I got it to work :) Looks like the EditorFor didn't work with EditorFor(m => m.firstName, new { data_binding = m.DataBindingAttributes }) . After I added a custom view template and used TextBoxFor, it seemed to work. Is there any way to do it with EditorFor? – Michael Brennan Jun 29 '11 at 20:04
  • Same question here - I changed it from EditorFor to TextBoxFor and it worked fine, but what lead me first to the post Crescent Fresh mentioned, and then this one, was trying to track down how to make this work with EditorFor. – Scott Silvi Feb 22 '12 at 19:00

1 Answers1

34

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.

Michael Brennan
  • 1,031
  • 8
  • 19