13

I tried this @Html.EditorFor(model => model.Name, " ", new { data_bind = "value:firstName" }); and other possible overloades but none of them seem to work.

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());
});

2
  • I would recommend of just using generic html and not use the @html.Editor helper. If you need the data from the model, use that to build your AppViewModel Commented May 23, 2013 at 18:08
  • What is the html output that your editor creates? Does it create a textbox or label? Is it missing the data-bind attribute that you specified? Commented May 23, 2013 at 18:25

2 Answers 2

32

Your 3rd parameter to EditorFor does not do what you think it should be doing.

See http://msdn.microsoft.com/en-us/library/ff406461(v=vs.98).aspx

EditorFor cannot add HTML attributes to the element. Use TextBoxFor instead:

@Html.TextBoxFor(model => model.Name, new { data_bind = "value:firstName" });
Sign up to request clarification or add additional context in comments.

1 Comment

For .Net Framework 4.6.1 and up I can confirm that @Html.EditorFor(m => m.FirstName, new { htmlAttributes = new { @class = "form-control", data_bind = "value: firstName", maxlength = 50 } }); works. data_bind is still key!
1

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:

@Html.EditorFor(t => t.name, "", new { fieldName = "name" })

Then in your editorTemplate you can have this:

@{
    var fieldName = ViewData.Where(v => v.Key == "fieldName").FirstOrDefault().Value;
}
@Html.TextBox("", Model, new { data_bind = "value:"+fieldName })

Hope this helps someone.

1 Comment

Make sure you use the markup to properly format code. It greatly helps with readability.

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.