I was wracking my brain the other day while trying to figure out how to get an editor template to properly bind to the ViewModel when using Html.EditorFor(m => m.ModelProperty). On the clientside it seemed to visually render ok, but something was amiss. What was wrong?
- The rendered input tag was missing the unobtrusive validation attributes that I was expecting.
- The name value of the input tag wasn't "ModelProperty" like I was expecting, but "ModelProperty.ModelProperty".
So why was this happening? Apparently, when inside an editor or display template, calling methods like Html.TextBox or Html.Label with the model's property name in it causes the template to bind to the dynamic ViewModel created for that template's instance, instead of the original ViewModel that the property originally came from.
To get around this, all you need to do from your template is call Html.TextBox(""), Html.Label(""), or any of the other helper methods. Just passing in an empty string fixes the problem!