Fabian Trottmann
Fabian Trottmann

Reputation: 224

MVC3 passing dictionary values to dropdownlist and binding associated key to the model

I am trying to create a mvc3 c# webapplication. What i'm trying to do, is to create a DropDownlist and passing a dictionary to it. The user in the webinterface should see the values of the dictionary and that works. But i dont want to bind the selected value to the model, instead i want the associated key. Is that somehow possible?

In the example, you see how i bind the selected value to the model:

@Html.DropDownListFor(model => model.EditDate, new SelectList(Versions.Values), Model.EditDate)

The Versions.Values are DateTimes (values of the dictionary). On Submit the selected Value is bind to model.EditDate. But i want to bind the associated key of the selected Value (values are id).

How can I do that?

Thanks in advance

Upvotes: 3

Views: 3707

Answers (1)

Brad Christie
Brad Christie

Reputation: 101614

You need to convert the Dictionary<T1,T2> to a SelectList, usually done using one of the Linq extensions. So, if you had:

Dictionary<Int32,DateTime> Versions = new Dictionary<Int32,DateTime> {
  { 1, new DateTime(2012, 12, 1) },
  { 2, new DateTime(2013, 1, 1) },
  { 3, new DateTime(2013, 2, 1) },
};

Then you could use:

@Html.DropDownListFor(model => model.EditDate,
  Versions.Select(x => new SelectListItem {
    Text = x.Value.ToShortDateString(),
    Value = x.Key.ToString(),
    Selected = x.Value == Model.EditDate
  })
)

(that's assuming model.EditDate is an int since you're now making the Keys of the dictionary the Value of the drop-down list.)

Upvotes: 4

Related Questions