我正在尝试以这种方式绑定 MVC3 中的下拉菜单。
Model
public static Dictionary<string, string> SexPreference()
{
var dict = new Dictionary<string, string>();
dict.Add("Straight", "S");
dict.Add("Gay", "G");
dict.Add("Bisexual", "BISEX");
dict.Add("Bicurious", "BICUR");
return dict;
}
控制器
ViewBag.SexPreference = MemberHandler.SexPreference();
View
@{
var itemsSexPreference = new SelectList(ViewBag.SexPreference, "Value", "Key", Model.sexpreference);
}
@Html.DropDownListFor(m => m.sexpreference, @itemsSexPreference)
下拉菜单没有选择所选值,不知道为什么。
你为什么要设置ViewBag.SexPreference
当你有模型时?忘记这个 ViewBag。此外,您还应该有 2 个属性来创建下拉列表:一个标量类型属性用于保存所选值,一个集合属性用于保存所选值的列表。现在,您似乎只使用一个并尝试将 DropDown 绑定到集合属性,这显然没有任何意义。
使用视图模型以正确的方式进行操作:
public class MyViewModel
{
public string SelectedSexPreference { get; set; }
public Dictionary<string, string> SexPreferences { get; set; }
}
您将在控制器操作中填充并传递给视图:
public ActionResult SomeAction()
{
var model = new MyViewModel();
// Set the value that you want to be preselected
model.SelectedSexPreference = "S";
// bind the available values
model.SexPreferences = MemberHandler.SexPreference();
return View(model);
}
在你的视野中:
@model MyViewModel
@Html.DropDownListFor(
m => m.SelectedSexPreference,
new SelectList(Model.SexPreferences, "Value", "Key")
)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)