如何访问HTML.Dropdownlist的Selected值



在asp.net mvc web应用程序中,我的视图中有以下内容:-

 @Html.DropDownList("siteName", ((IEnumerable<TMS.Models.SDOrganization>)ViewBag.sites).Select(option => new SelectListItem {
            Text = (option == null ? "None" : option.NAME), 
            Value = option.NAME,
            Selected = (Model != null) && (Model.Resource.SiteDefinition != null ) && (Model.Resource.SiteDefinition.SDOrganization != null) && (option.NAME.ToUpper() == Model.Resource.CI.SiteDefinition.SDOrganization.NAME.ToUpper())
        }), "Choose...")

但当前下拉列表将始终显示"选择",而不是显示与当前模型对象关联的值。记住,如果我直接在视图@Model.Resource.CI.SiteDefinition.SDOrganization.NAME.ToUpper();中写下以下内容,它将显示正确的结果。

您想要使用DropDownList方法的签名:

public static MvcHtmlString DropDownList(
    this HtmlHelper htmlHelper,
    string name,
    IEnumerable<SelectListItem> selectList,
    string optionLabel
)

并且,SelectList类的这个构造函数:

public SelectList(
    IEnumerable items,
    Object selectedValue
)

所以,这样做吧:

@Html.DropDownList("siteName", new SelectList(ViewBag.sites, Model.Resource.CI.SiteDefinition.SDOrganization.NAME), "None")

但是,请确保ViewBag.sites没有任何空值。此外,请遵循标准命名约定。请使用"SiteName"而不是"SiteName",并使用"Sites"代替"Sites"。最重要的是,将SiteName添加到ViewModel中,并使用强类型的DropDownList版本,如下所示:

@Html.DropDownListFor(model => model.SiteName, new SelectList(ViewBag.Sites, Model.SiteName), "None")

最新更新