为什么DropDownListFor的默认值无法正常工作?

问题描述 投票:2回答:2

无论出于何种原因,我的Html.DropDownListFor的默认值不起作用:

@Html.DropDownListFor(model => model.DomainList,
    new SelectList(Model.DomainList, "DomainId", "Name", Model.SingleDomain.DomainId),
    new { @class = "form-control" })

知道为什么吗?

UPDATE

在下面的答案中,我将我的代码更新为以下内容:

@Html.DropDownListFor(model => model.SelectedDomain, 
    new SelectList(Model.DomainList, "DomainId", "Name", Model.SelectedDomain),
    "Select a Domain", 
    new { @class = "form-control" })
asp.net-mvc-5 html.dropdownlistfor
2个回答
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,但我认为要么应该工作

这是另一个很好的例子:

MVC3 DropDownListFor - a simple example?


0
投票

如果有人遇到Html.DropdownList的麻烦,请记住

@Html.DropDownList("Country", ViewBag.Country as List<SelectListItem>) - >不选择默认值

@Html.DropDownList("Countries", ViewBag.Country as List<SelectListItem>) - >选择默认值

有关更多详细信息,请参阅:http://www.binaryintellect.net/articles/69395e7d-7c7c-4318-97f5-4ea108a0da97.aspx

© www.soinside.com 2019 - 2024. All rights reserved.