Fernando Vezzali
Fernando Vezzali

Reputation: 2319

How to use html helper for a generic collection?

I have a strongly typed view, it is an IEnumerable. I am trying to use the DisplayFor helper for a collection, which is a property of my model. The helper works perfectly when iterating my model, but when I try to use it for a sub collection, it crashes.

My first attempt was writing something like this:

@Html.DisplayFor(modelItem =>
item.Months.Where(x=>x.Equals(month)).Select(x=>x.Amount))

But then I got this run-time error: "Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions."

That is my View's Code:

@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name) @* It works perfectly here*@
        </td>

        @foreach (var month in item.Months)
        {
            <td>
                @month.Amount @* How can I use DisplayFor helper here ? *@
            </td>
        }

    </tr>
}

That is my Model's Code:

public class Department
{
    public string Name { get; set; }
    public List<Month> Months { get; set; }
}

public class Month
{
    public int number { get; set; }
    [DataType(DataType.Currency)]
    public decimal Amount { get; set; }
}

Upvotes: 2

Views: 861

Answers (2)

You should consider using Partial Views.

@Html.Partial("_months", Months)

Then your partial view could be something like below:

@model IEnumerable<Months>

<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.number)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Amount)
        </th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.number)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Amount)
        </td>
    </tr>
}

</table>

Upvotes: 4

Konamiman
Konamiman

Reputation: 50323

Try this:

@for(int i=0; i<item.Months.Count; i++)
{
    <td>
        @Html.DisplayFor(modelItem => item.Months[i].Amount)
    </td>
}

Upvotes: 3

Related Questions