我终于成功了。即使我的语法;当我把变量传递给
public IEnumerable FeaturedChoices(Spotlight spotlight)
不管怎样,即使我明确地标记
Selected = true
. 如果有人能回答为什么会这样我会很感激
唯一的办法
selected="selected"
如果我做了
FeaturedChoices
视图模型:
//
// 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
{
get
{
return feature.Select(f => new SelectListItem
{
Text = f.Key,
Value = f.Value.ToString(),
Selected = IsSelected(this.Spotlight.Featured, f.Key)
});
}
}
private bool IsSelected(bool featured, string val)
{
bool result = false;
if (String.Compare(val, "True") == 0 && featured)
result = true;
else if (String.Compare(val, "False") == 0 && !featured)
result = true;
return result;
}
// constr
public SpotlightFormViewModel(Spotlight spotlight)
{
Spotlight = spotlight;
}
}
控制器:
public ActionResult Edit(int id)
{
Spotlight spotlight = spotlightRepository.GetSpotlight(id);
return View(new SpotlightFormViewModel(spotlight));
}
查看:
<div class="editor-label">
<%: Html.LabelFor(model => model.Spotlight.Featured) %>
</div>
<div class="editor-field">
<%: Html.DropDownListFor(model => model.FeaturedMenu, Model.FeaturedChoices)%>
<%: Html.ValidationMessageFor(model => model.Spotlight.Featured) %>
</div>