Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding a dropdownlist in mvc3 to a dictionary?

What am I missing here?

ViewModel:

public class ViewModel
{
    public IDictionary<int, string> Entities { get; set; }
    public int EntityId { get; set; }
}

Controller:

    public override ActionResult Create(string id)
    {
        ViewModel = new ViewModel();

        IEnumerable<Entity> theEntities = (IEnumerable < Entity >)db.GetEntities();
        model.Entities= theEntities.ToDictionary(x => x.Id, x => x.Name);

        return View(model);            
    }

View:

<div class="editor-field">@Html.DropDownListFor(model => model.EntityId,
    new SelectList(Model.Entities, "Id", "Name"))</div>
</div>

Error:

DataBinding: 'System.Collections.Generic.KeyValuePair....does not contain a property with the name 'Id'

like image 884
Mariah Avatar asked Apr 02 '12 21:04

Mariah


1 Answers

KeyValuePair has properties Key and Value. You are better off declaring Entities as type IEnumerable<Entity>, then your view would work as-is:

public class ViewModel
{
    public IEnumerable<Entity> Entities { get; set; }
    public int EntityId { get; set; }
}

OR, if you really need to use a Dictionary<>, change your view:

<div class="editor-field">
    @Html.DropDownListFor(model => model.EntityId, new SelectList(Model.Entities, "Key", "Value"))
</div>
like image 113
Keith Avatar answered Sep 24 '22 11:09

Keith