Editor Templates for List<string>

Richard picture Richard · Mar 14, 2011 · Viewed 7.8k times · Source

I am looking to create a generic editor for some basic models in my ASP.NET MVC3 site. Now they can contain strings, booleans, enums and List collections. What I want to do is extend the default editor templates to recognise List and show a custom editor which can add and remove strings to this list. All the others work just fine.

As I cannot name the file List.cshtml of course Is there a way to be able to get this to work? Also why are enums not drop down lists of the enum by default?

I know I can create model named templates but I do not know the class names until runtime.

Thanks for any help and guidance.

Answer

Darin Dimitrov picture Darin Dimitrov · Mar 14, 2011

You can name the editor template Foo.cshtml where Foo is the type of the list: List<Foo>. Then simply:

@Html.EditorFor(x => x.FooList)

and if FooList is an IEnumerable<Foo> your editor template will be automatically rendered for each element of this list. So if you already have editor templates for the basic data types such as String, Decimal, DateTime, ... when you do @Html.EditorFor(x => x.SomeList) your editor templates will be picked up.