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?

3
  • 8
    See stackoverflow.com/questions/2520487/… Commented Jun 29, 2011 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? Commented Jun 29, 2011 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. Commented Feb 22, 2012 at 19:00

1 Answer 1

35

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Worked for me! Thanks for this. A little hidden, yes, but makes sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.