ASP.net MVC - Display Template for a collection

前端 未结 4 1261
自闭症患者
自闭症患者 2020-12-01 04:19

I have the following model in MVC:

public class ParentModel
{
    public string Property1 { get; set; }
    public string Property2 { get; set; }

    public         


        
4条回答
  •  情话喂你
    2020-12-01 04:45

    The actual "valid answer" is -IMHO- not correctly answering the question. I think the OP is searching for a way to have a list template that triggers without specifying the UIHint.

    Magic stuff almost does the job

    Some magic loads the correct view for a specified type.
    Some more magic loads the same view for a collection of a specified type.
    There should be some magic that iterates the same view for a collection of a specified type.

    Change the actual behavior?

    Open your favorite disassembler. The magic occurs in System.Web.Mvc.Html.TemplateHelpers.ExecuteTemplate. As you can see, there are no extensibility points to change the behavior. Maybe a pull request to MVC can help...

    Go with the actual magic

    I came up with something that works. Create a display template ~/Views/Shared/DisplayTemplates/MyModel.cshtml.

    Declare the model as type object.

    If the object is a collection, iterate and render the template again. If it's not a collection, then show the object.

    @model object
    
    @if (Model is IList)
    {
        var models = (IList)Model;
    
      @foreach (var item in models) { @Html.Partial("DisplayTemplates/MyModel", item) }
    } else { var item = (MyModel)Model;
  • @item.Name
  • } }

    Now DisplayFor works without UIHint.

提交回复
热议问题