ASP.NET MVC 2 - HTML.EditorFor() and Custom EditorTemplates

Nathan Taylor picture Nathan Taylor · Aug 5, 2009 · Viewed 23.8k times · Source

With MVC 2's addition of the HtmlHelper EditorFor() it is not possible to create strongly typed Display and Editor templates for a given Model object and after fiddling with it I am a bit stumped as to how to pass additional Model data to the editor without losing the strong-typing of the editor control.

Classic Example: Product has Category. ProductEditor has a DropDownList for Category containing the names of all Categories. The ProductEditor is strongly typed to Product and we need to pass in the SelectList of Categories as well as the Product.

With a standard view we would wrap the Model data in a new type and pass that along. With the EditorTemplate we lose some of the standard functionality if we pass in a mixed Model containing more than one object (first thing I noticed was all of the LabelFor/TextBoxFor methods were producing entity names like "Model.Object" rather than just "Object").

Am I doing it wrong or should Html.EditorFor() have an additional ViewDataDictionary/Model parameter?

Answer

Haacked picture Haacked · Aug 8, 2009

You can either create a custom ViewModel which has both properties OR you'll need to use ViewData to pass that information in.