ross dickinson: web and desktop software developer

ASP MVC's EditorFor and DisplayFor Templates

by Ross on November 18, 2011 at 1:23 PM under ASP.Net

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?

  1. The rendered input tag was missing the unobtrusive validation attributes that I was expecting.
  2. 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!

About the author

rossisdead is a 26 year old web and desktop software developer from New Jersey. He has two cats and likes long walks on the beach.

On Stackoverflow

On Stackoverflow Careers

On Codeplex

On Github