I've got a table that stores a True/False value as a sqlserver bit field (Featured
). First, is there a better way to generate a dropdown list for this other than manually?
Second, here's what I've got so far which works but does not add selected="selected"
to any items in the DDL.
Edit 1: I've updated this example according to the answer suggested and it results in a run-time error :( Edit 2: Using it like a function works (with and without the cast) but selected="selected" is still not being added.
Model:
//
// View models
public class SpotlightFormViewModel
{
// props
public Spotlight Spotlight { get; private set; }
public SelectList FeaturedMenu { get; private set; }
static IDictionary<string, int> feature = new Dictionary<string, int>(){
{"True", 1},
{"False", 0},
};
public IEnumerable<SelectListItem> FeaturedChoices(Spotlight spotlight)
{
return feature.Select(f => new SelectListItem
{
Text = f.Key,
Value = f.Value.ToString(),
Selected = spotlight.Featured,
});
}
// constr
public SpotlightFormViewModel(Spotlight spotlight)
{
Spotlight = spotlight;
FeaturedMenu = new SelectList(FeaturedChoices(spotlight));
}
}
Controller:
public ActionResult Edit(int id)
{
Spotlight spotlight = spotlightRepository.GetSpotlight(id);
return View(new SpotlightFormViewModel(spotlight));
}
View:
<div class="editor-label">
<%: Html.LabelFor(model => model.Spotlight.Featured) %>
</div>
<div class="editor-field">
<%: Html.DropDownListFor(model => model.FeaturedMenu, Model.FeaturedChoices(Model.Spotlight))%>
<%: Html.ValidationMessageFor(model => model.Spotlight.Featured) %>
</div>