Editor Templates for List

2019-04-10 00:44发布

问题:

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.

回答1:

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.