MVC DropDownList选中的值不起作用
我正在使用MVC 5。
我有我的ViewBag列表
ViewBag.TitleList = new SelectList((new string[] { "Mr", "Miss", "Ms", "Mrs" }), contact.Title); //contact.Title has selected value.
然后我尝试将数组转换为SelectListItem ( to no avail)
在视图上它看起来像
@Html.DropDownListFor(model => model.Title, ViewBag.TitleList as SelectList, "Select")
我也试过了
@Html.DropDownList("Title", ViewBag.TitleList as SelectList, "Select")
列表已成功加载,但未Selected Value is Not selected
。 如何解决这个问题?
更新罪魁祸首是ViewBag.Title匹配我的模型。标题。 将我的模型属性重命名为其他内容并且有效。 Arrgh!
设置控制器中Title
属性的值:
ViewBag.TitleList = new SelectList(new string[] { "Mr", "Miss", "Ms", "Mrs" }); viewModel.Title = "Miss"; // Miss will be selected by default
另一个可能的原因(以及基于以下评论的正确原因)是ViewData["Title"]
被另一个值覆盖。 将Title
属性的Title
更改为任何其他属性,一切都应该有效。
如果未指定值(即“Id”),DropDownListFor有时会表现不正常。 试试这个:
public class FooModel { public int Id { get; set; } public string Text { get; set; } } var temp = new FooModel[] { new FooModel {Id = 1, Text = "Mr"}, new FooModel {Id = 2, Text = "Miss"}, new FooModel {Id = 3, Text = "Ms"}, new FooModel {Id = 4, Text = "Mrs"} }; ViewBag.TitleList = new SelectList(temp, "Id", "Text", 2);
编辑:其他解决方案
var temp = new [] { new SelectListItem {Value = "Mr", Text = "Mr"}, new SelectListItem {Value = "Miss", Text = "Miss"}, new SelectListItem {Value = "Ms", Text = "Ms"}, new SelectListItem {Value = "Mrs", Text = "Mrs"} }; ViewBag.TitleList = new SelectList(temp, "Value", "Text", "Miss");