繁体   English   中英

如何为Html.DropDownListFor设置默认选择值

[英]How to set default selected value for Html.DropDownListFor

    @if (HttpContext.Current.Request.Cookies[MyCookies.SelectedRegion] != null)
     {
       var defaultRegionValue = HttpContext.Current.Request.Cookies[MyCookies.SelectedRegion].Value;
        @Html.DropDownListFor(m => m.SelectedRionName, Model.RegionList, defaultRegionValue)
     }
     else
     {
       @Html.DropDownListFor(m => m.SelectedRionName, Model.RegionList, "Select")
     }

我的视图中有上述示例,该示例应该使用区域列表填充Dropdownlist。 选择一个区域后,我将该区域设置为cookie中的默认区域。

下次他们访问该应用程序时,我正在检索cookie值,以便可以在变量“ defaultRegionValue ”中预选择一个与我的cookie值匹配的区域(在下拉列表中)。

我上面的代码的问题是“ defaultRegionValue ”作为DataTextField出现在下拉列表中,但我希望它作为DataTextValue。

我不想在变量“ defaultRegionValue”中显示真实的字符串值,而是希望下拉列表将其读取为selectedValue,然后显示对应的文本值。

目前是显示值,所选值是空值。 如何正确设置?

下面是我的RegionList定义

 public SelectList RegionList
    {
        get
        {
            Dictionary<string, string> items = this.qryRegionList.ToDictionary(k => k.RegionName, v => v.RegionID);
            return new SelectList(items.OrderBy(k => k.Key), myConstants.Value, myConstants.Key);
        }
    }

SelectList具有构造函数重载,该重载采用参数中的选定值。

您可以像这样创建新的SelectList:

@Html.DropDownListFor(m => m.SelectedRionName, 
                           new SelectList(Model.RegionList,
                                          "Value",
                                          "Text",
                                          defaultRegionValue))

将SelectedRionName设置为等于您的cookie值,而不是声明defaultRegionValue。

@if (HttpContext.Current.Request.Cookies[MyCookies.SelectedRegion] != null)
 {
    Model.SelectedRionName = HttpContext.Current.Request.Cookies[MyCookies.SelectedRegion].Value;
    @Html.DropDownListFor(m => m.SelectedRionName, Model.RegionList)
 }
 else
 {
   @Html.DropDownListFor(m => m.SelectedRionName, Model.RegionList, "Select")
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM