Search code examples
c#asp.net-mvcrazorienumerableicollection

ICollection<> inside ICollection<> in Razor - can't retrieve the model names


I'm wondering how to resolve the problem. I'm developing an ASP.NET MVC app

I have a models

public class SearcherString
{
    public int ID { get; set; }
    public string Description { get; set; }
    public virtual ICollection<Path> Path { get; set; 
    public SearcherString()
    {
        Path = new List<Path>();
    }
}

public class Path
{
    public int ID { get; set; }
    public int CategoryID { get; set; }
    public string CategoryName { get; set; }
}

I'm passing it in my Controller (I'm writing my model into my database and then I'm retrieving it)

public ActionResult Index()
{
    return View(db.SearchersString.ToList()
}

And I have a View with:

@model IEnumerable<App.Models.SearcherString>

The problem is in my View, I can't display the names from Path model (CategoryID, CategoryName)

I tried to do:

<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Description)
        </th>
        @foreach (var item in Model)
        {
            foreach (var path in item.Path)
            {
                <th>
                    @Html.DisplayName(path.CategoryID.ToString())
                </th>
                <th>
                    @Html.DisplayName(path.CategoryName)
                </th>
            }
        }
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Description)
            </td>
            @foreach (var path in item.Path)
            {
                <td>
                    @Html.DisplayFor(modelItem => path.CategoryID)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => path.CategoryName)
                </td>
            }
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
                @Html.ActionLink("Details", "Details", new { id = item.ID }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.ID })
            </td>
        </tr>
    }
</table>

But I have only: enter image description here

Could someone help me with this problem?

Edit:

Is there a way to change the Html.DisplayName to Html.DisplayNameFor here?

@Html.DisplayName(path.CategoryID.ToString())

Solution

  • You should include navigation property to your query:

    public ActionResult Index()
    {
        return View(db.SearchersString.Include(c=>c.Path).ToList()
    }