Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Nested Model Collection

I am new to MVC and I am trying to display information from a nested model collection on the page.

so my model is as follow:

public partial class Parent
{
    public Parent()
    {
        this.Childs = new HashSet<Child>();
     }

    public int ParentID { get; set; } 
     public string Name { get; set; } 

    public virtual ICollection<Child> Childs { get; set; }
 }

To display the information on the Parent view i used :

@foreach (Child c in Model.Childs)
{
    @c.Name 
}

The above works but i would like to use a different view for the childs so i have tried the following:

@Html.DisplayFor(model => model.Childs)

and defined the following view:

@model WebApplication1.Models.Child

<div>
      @Html.DisplayFor(model => model.Name)
</div>

This doesn't work and what I am getting is a System.Data.Entity.DynamicProxies displayed instead of the list of child names. I have read that this is because MVC5 doesn't know what view to use. I have tried specifying the view in the Display for as @Html.DisplayFor(model => model.Childs, "ViewName1.cshtml") but that didn't help at all.

In addition to the above I would like to use something similar for @Html.EditorFor(model => model.Childs).

like image 574
panais Avatar asked Dec 19 '22 13:12

panais


1 Answers

Start by creating a DisplayTemplates sub-folder in your Parent view folder. Then create a view in that folder called Child.cshtml.

Child.cshtml

@model WebApplication1.Models.Child

@Model.Name
...more HTML markup if needed

Then all you do is call @Html.DisplayFor(m => m.Childs) and the framework will do the rest for you. Note that if you use the overload that lets you specify which view to use, the loop will not be done automatically for you.

Repeat the same process for editor templates, with a EditorTemplates folder and following the same conventions (view name = type name) for naming your views.

like image 134
dom Avatar answered Dec 29 '22 00:12

dom