ASP.net MVC - Display Template for a collection

前端 未结 4 1258
自闭症患者
自闭症患者 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 05:02

    In my question about not getting output from views, I actually have an example of how to template a model with a collection of child models and have them all render.

    ASP.NET Display Templates - No output

    Essentially, you need to create a model that subclasses List or Collection and use this:

    @model ChildModelCollection 
    
    @foreach (var child in Model)
    {
        Html.DisplayFor(m => child);
    }
    

    In your template for the collection model to iterate and render the children. Each child needs to strongly-typed, so you may want to create your own model types for the items, too, and have templates for those.

    So for the OP question:

    public class ChildModelCollection : Collection { }
    

    Will make a strongly-typed model that's a collection that can be resolved to a template like any other.

提交回复
热议问题