Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding DropDownListFor helper to a dictionary

Tags:

asp.net-mvc

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.

like image 206
dev.e.loper Avatar asked Oct 04 '11 19:10

dev.e.loper


2 Answers

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)
like image 196
Darin Dimitrov Avatar answered Nov 15 '22 06:11

Darin Dimitrov


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>
like image 38
Rana Ahsan Avatar answered Nov 15 '22 06:11

Rana Ahsan