Collection of nested MVC models

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

so my model is as follows:

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 in 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 children, so I tried the following:

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

and defined the following form:

@model WebApplication1.Models.Child

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

This does not work, and I get the System.Data.Entity.DynamicProxies view instead of the list of child names. I read that this is because MVC5 does not know which kind to use. I tried to indicate the view in Drive as @Html.DisplayFor(model => model.Childs, "ViewName1.cshtml"), but that did not help.

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

+4
3

DisplayTemplates Parent. Child.cshtml.

Child.cshtml

@model WebApplication1.Models.Child

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

, , @Html.DisplayFor(m => m.Childs), . : , , , .

, EditorTemplates ( = ) .

+5

Razor, . - ( ChildViewName ):

@foreach (Child c in Model.Childs)
{
    @Html.Partial("ChildViewName", c)
}
+5

, , , asp.net mvc, . @panais , . , .

  • EditorTemplates.
  • DisplayTemplates.
  • .
+1

Source: https://habr.com/ru/post/1547443/


All Articles