I'm creating and populating a Dictionary and want to bind it to drop down list by using DropDownListFor helper method.
How do I map that dictionary's key
and value
to dropdown?
It looks like I should be able to do something like:
@Html.DropDownListFor(o => o.key, o => o.value, MyDictionary);
It seems like the first parameter should be a LINQ statement that maps key/value pair and second parameter is dictionary itself.
You cannot bind a dropdown list to a dictionary. It doesn't make sense. In order to generate a dropdown list you need 2 things: a scalar property to bind the selected value to and a collection to bind the options of the dropdown list. You only have the second of those two things which is the dictionary. So you cannot use a strongly typed helper.
You could do the following ugliness:
@Html.DropDownList("SelectedValue", new SelectList(MyDictionary, "Key", "Value"))
but of course a far better approach would be to use a view model:
public class MyViewModel
{
public string SelectedValue { get; set; }
public SelectList Values { get; set; }
}
which you would populate in your controller action:
public ActionResult Foo()
{
Dictionary<string, string> dic = ...
var model = new MyViewModel
{
Values = new SelectList(dic, "Key", "Value")
};
return View(model);
}
and finally in your strongly typed view:
@model MyViewModel
@Html.DropDownListFor(x => x.SelectedValue, Model.Values)
You should try like this:
In Controller
ViewBag.hour = new SelectList(Hours.Values);
void AddHours()
{
Hours = new Dictionary<int, string>();
Hours.Add(00, "00");
Hours.Add(01, "01");
Hours.Add(02, "02");
}
In Views
<div class="col-md-2">
@Html.DropDownList("Hours", new SelectList(ViewBag.hour.Items), "Hours", htmlAttributes: new { @class = "form-control", placeholder = "Hours" })
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With