blacksaibot
blacksaibot

Reputation: 285

Using dictionaries with ASP.NET MVC4

In my view:

<tbody>
    @foreach (var item in Model)
    {

        foreach (KeyValuePair<string, Dictionary<string, int>> fs in item.dicFS)
        {
            <tr>
                <td>@Html.DisplayFor(modelItem => fs.Key.ToString())</td>

                @foreach (KeyValuePair<string, int> lbl in item.dicFS[fs.ToString()])
                {
                    <td>@Html.DisplayFor(modelItem => lbl.Value.ToString())</td>
                }

            </tr>
        }
    }
</tbody>

Error:

An exception of type 'System.InvalidOperationException' occurred in   System.Web.Mvc.dll but was not handled in user code

Additional information: Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

This is the line highlighted when the application crashes

 <td>@Html.DisplayFor(modelItem => fs.Key.ToString())</td>

My model contains a public dictionary that contains a string key and a dictionary value (nested dictionary)

    public Dictionary<string, Dictionary<string, int>> dicFS;

The keys and the nested dictionary are initialized and values are assigned by a method within the model.

Am I not allowed to use dictionaries? Do I have to convert my model's data type to a nested array instead of using nested dictionary?

Thanks in advance for your help!

Upvotes: 0

Views: 39

Answers (1)

Dola
Dola

Reputation: 1483

You cannot use .ToString() inside DisplayFor() method.

Just remove the .ToString() and you should be good

<tbody>
    @foreach (var item in Model)
    {

        foreach (KeyValuePair<string, Dictionary<string, int>> fs in item.dicFS)
        {
            <tr>
                <td>@Html.DisplayFor(modelItem => fs.Key)</td>

                @foreach (KeyValuePair<string, int> lbl in item.dicFS[fs.ToString()])
                {
                    <td>@Html.DisplayFor(modelItem => lbl.Value)</td>
                }

            </tr>
        }
    }
</tbody>

Upvotes: 1

Related Questions