MVC DropDownList的选定值不工作 [英] MVC DropDownList selected value not working
问题描述
我使用MVC 5。
我有我的名单ViewBag为
I have my ViewBag for list as
ViewBag.TitleList = new SelectList((new string[] { "Mr", "Miss", "Ms", "Mrs" }), contact.Title);
//contact.Title has selected value.
然后我尝试了数组 SelectListItem转换(无济于事)
在View它看起来像
@Html.DropDownListFor(model => model.Title, ViewBag.TitleList as SelectList, "Select")
也是我试过
@Html.DropDownList("Title", ViewBag.TitleList as SelectList, "Select")
该列表加载成功,但选定值未选择
。
如何解决这个问题呢?
The list loads successfully but the Selected Value is Not selected
.
How to Fix this problem?
更新
罪魁祸首是ViewBag.Title匹配我的model.Title。我改名模型属性到别的和它的工作。 Arrgh!
Update The culprit was ViewBag.Title matching my model.Title. Renamed my model property to something else and it worked. Arrgh!
推荐答案
在控制器中的标题
属性的设定值:
Set value of the Title
property in the controller:
ViewBag.TitleList = new SelectList(new string[] { "Mr", "Miss", "Ms", "Mrs" });
viewModel.Title = "Miss"; // Miss will be selected by default
另一个可能的原因(和正确的基础上,下面的评论)是计算机[标题]
被另一个值覆盖。更改标题
属性的名称任何其他一切都应该工作。
Another possible reason (and the correct one, based on the comments below) is that ViewData["Title"]
is overridden by another value. Change name of the Title
property to any other and everything should work.
这篇关于MVC DropDownList的选定值不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!