MVC3 Razor Editor / Show Templates and Generics

There were a few questions regarding mvc templates and generics, however, there seems to be nothing to do with what I'm looking for. Consider the following models:

namespace MyNamespace
{
    public class ModelBase { /* Not important for example */ }

    public class MyModel : ModelBase
    {
        public string Name { get; set; }
    }

    public class MyViewModel
    {
        public IEnumerable<ModelBase> Data { get; set; }
    }
}

And the controller:

public class HomeController : Controller
{
    public ActionResult Index 
    {
        return View(new MyViewModel { Data = new List<MyModel>() })
    }
}

A Razor view Views / Home / Index.cshtml will look like this:

@model MyNamespace.MyViewModel
@Html.EditorFor(m => m.Data)

Nothing special. If I need a display or editor template, I can create a file in the Views / Shared / EditorTemplate section or in the Views / Home / EditorTemplates section named MyModel.cshtml and it will find it correctly.

What if I want to do something different for each ModelBase implementation when displaying a list? The mvc viewer will find the List'1.cshtml template correctly in any of the above paths. However, I need to make a template for List`1 [MyModel] .cshtml

. , ( ):

  • List`1 [MyModel].cshtml
  • List`1 [[MyModel]]. Cshtml
  • List`1 [MyNamespace.MyModel].cshtml
  • List`1 [[MyNamespace.MyModel]]. Cshtml

, . , , , - , List`1.cshtml , .

+3
3

, - :

return View(MyModel.GetType().Name, new MyViewModel { Data = new List<MyModel>() })

, View .

+1

, , - ( , , )

UIHintAttribute

public class MyViewModel
{
    [UIHint("MyModel")]
    public IEnumerable<ModelBase> Data { get; set; }
}
+6

You can do this in the main view:

@model MyViewModel
@Html.EditorFor(x => x.Data)

and then:

  • ~/Views/Shared/EditorTemplates/MyModel.cshtml:

    @model MyModel
    ...
    
  • ~/Views/Shared/EditorTemplates/MyOtherModel.cshtml(where obviously MyOtherModelcomes from ModelBase):

    @model MyOtherModel
    ...
    

etc. ASP.NET MVC takes care of going through the Data property and choosing the right template based on the runtime type of each item in this collection.

0
source

All Articles