"Key has already been added"

Feb 25, 2013 at 2:51 PM
Edited Feb 25, 2013 at 2:51 PM
I have a situation where I need to show data from a list inside a list in a grid.

For example:
@Html.Grid(Model).Columns(columns =>
    columns.Add(model => model.MyModel.Version).Titled("column1");
        columns.Add(model => model.MyModel.Alist[0].aValue).Titled("column2");
        columns.Add(model => model.MyModel.Alist[1].aValue).Titled("column3");
I get the following error message:
An item with the same key has already been added.
How can I make this work?

Feb 26, 2013 at 3:32 AM

Grid.Mvc do not support indexers yet. But there are two ways to solve this problem:

If you don't need sorting and filtering feature for this columns you can add not-binded columns, and specify rendering function:
columns.Add().Titled("column2").RenderValueAs(model => model.MyModel.Alist[0].aValue.ToString());
columns.Add().Titled("column2").RenderValueAs(model => model.MyModel.Alist[1].aValue.ToString());
The second way - defined additional properties in you model that will returns values from you array:
public YourModelType AlistValue0
    get { return MyModel.Alist[0].aValue; }
public YourModelType AlistValue1
    get { return MyModel.Alist[1].aValue; }
And bind the columns to this properties:
columns.Add(model => model.AlistValue0).Titled("column2");
columns.Add(model => model.AlistValue1).Titled("column3");
I will try to fix this issue in the next release of Grid.mvc