MVC3 Razor Editor/Display templates and generics

廉价感情. 提交于 2019-12-06 00:46:17

I haven't checked this code but I would create different Views for each subtype and do something dumb like:

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

So that your View matches the name of your type.

A very late response, useful if someone else bump in this very same question (as I did a few moments ago trying to remember how to do this)

You can use the UIHintAttribute to define the name of the editor

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

You could do this in the main view:

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

and then have:

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

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

    @model MyOtherModel
    ...
    

and so on ... ASP.NET MVC will take care of looping through the Data property and pick the correct template based on the runtime type of each element of this collection.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!