Привязка выпадающего списка в mvc3 к словарю? - PullRequest
5 голосов
/ 03 апреля 2012

Что мне здесь не хватает?

ViewModel:

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

Контроллер:

    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);            
    }

Вид:

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

Ошибка:

Привязка данных: 'System.Collections.Generic.KeyValuePair .... не содержать свойство с именем 'Id'

1 Ответ

14 голосов
/ 03 апреля 2012

KeyValuePair имеет свойства Key и Value.Вам лучше объявить Entities как тип IEnumerable<Entity>, тогда ваше представление будет работать как есть:

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

ИЛИ, если вам действительно нужно использовать словарь <>, измените ваше представление:

<div class="editor-field">
    @Html.DropDownListFor(model => model.EntityId, new SelectList(Model.Entities, "Key", "Value"))
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...