Search code examples
asp.net-mvcmvc-editor-templatesrazor-2

EditorTemplate Naming Convention for Collection model classes


I have a model property that is declared as type List<MyClass>.

public class MyModel
{
    List<MyClass> MyProperty { get; set; }
}

I want to be able to display/edit the property using Razor templates. My question is, how I name an EditorTemplate view so that I can display the property using the normal syntax:

@model MyModel
@Html.DisplayFor(m => m.MyProperty)

I know that I can create a view called MyClass.cshtml that will be used for the type MyClass, but how do I create a template for the list?


Solution

  • You could use the [UIHint] attribute:

    public class MyModel
    {
        [UIHint("TemplateForTheList")]
        public List<MyClass> MyProperty { get; set; }
    }
    

    or specify the template name as second parameter to the DisplayFor helper:

    @model MyModel
    @Html.DisplayFor(m => m.MyProperty, "TemplateForTheList")
    

    and then have a TemplateForTheList.cshtml template:

    @model List<MyClass>
    ...
    

    In this case the templating engine will not render the template for each element of the collection property. It will simply pass the collection itself to the template.