ASP.NET MVC 2 - Populate drop down list from a Dictionary
I'm trying to poplulate a drop down list in MVC 2 from a Dictionary{string, string}. My code below, that is not quite right...
stat开发者_Python百科es is the Dictionary. Help
<tr>
<td class="formtext">
<%: Html.LabelFor(m => m.State)%> <strong>*</strong>
</td>
<td align="left">
<%= Html.DropDownList("statesDropDown", null, null, new { @class = "ddlAttributeGroups" })%>
</td>
</tr>
ActionResult:
var states = new States().GetStates();
var statesDropDown = new SelectList(states, states.Keys.ToString(), states.Values.ToString());
ViewData["statesDropDown"] = statesDropDown;
Why are you using ViewData instead of view models and strongly typed views which would make your code much more clear/safer/Intellisense enabled, ...? Why are you using dictionaries instead of some simpler types? Like for example a view model:
public class MyViewModel
{
public string SelectedState { get; set; }
public IEnumerable<SelectListItem> States { get; set; }
}
and a controller:
public ActionResult Foo()
{
var states = new States().GetStates();
var model = new MyViewModel
{
States = states.Select(x => new SelectListItem
{
Value = x.Key,
Text = x.Value
})
};
return View(model);
}
and a strongly typed view:
<%= Html.DropDownList(
x => x.SelectedState,
new SelectList(Model.States, "Value", "Text"),
null,
new { @class = "ddlAttributeGroups" }
) %>
See how easy it is?
精彩评论