无论出于何种原因,我的Html.DropDownListFor的默认值都不起作用:
@Html.DropDownListFor(model => model.DomainList,
new SelectList(Model.DomainList, "DomainId", "Name", Model.SingleDomain.DomainId),
new { @class = "form-control" })
知道为什么吗?
更新
通过以下答案,我将代码更新为以下内容:
@Html.DropDownListFor(model => model.SelectedDomain,
new SelectList(Model.DomainList, "DomainId", "Name", Model.SelectedDomain),
"Select a Domain",
new { @class = "form-control" })
答案 0 :(得分:7)
试试这个:
在ViewModel中,添加一个整数来存储选定的域ID:
public int SelectedDomainId { get; set; }
将DropDownListFor更改为:
@Html.DropDownListFor(model => model.SelectedDomainId,
new SelectList(Model.DomainList, "DomainId", "Name", Model.SingleDomain.DomainId),
new { @class = "form-control" })
现在回发后,所选的ID将发布在SelectedDomainId。
或者,您可以将单个域对象添加到VM(以指示选择了哪个):
public Domain SelectedDomain { get; set; }
将DropDownListFor更改为:
@Html.DropDownListFor(model => model.SelectedDomain,
new SelectList(Model.DomainList, "DomainId", "Name", Model.SingleDomain.DomainId),
new { @class = "form-control" })
我通常使用所选的ID,但我认为要么应该工作
这是另一个很好的例子:
答案 1 :(得分:0)
如果有人遇到问题Html.DropdownList
请记住
@Html.DropDownList("Country", ViewBag.Country as List<SelectListItem>)
- &gt;不选择默认值
@Html.DropDownList("Countries", ViewBag.Country as List<SelectListItem>)
- &gt;选择默认值
有关详细信息,请参阅:http://www.binaryintellect.net/articles/69395e7d-7c7c-4318-97f5-4ea108a0da97.aspx