如何设置Html.DropDownListFor的默认选定值 [英] How to set default selected value for Html.DropDownListFor

查看:346
本文介绍了如何设置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中的默认区域.

I have the above sample in my view which is supposed to populate a Dropdownlist with a list of regions. Once a region is selected, i set that region as their default region in a cookie.

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

The next time they visit the application, i'm retrieving the cookie value such that i can pre-select a region (in the dropdown) which matches my cookie value in variable "defaultRegionValue".

我上面的代码的问题是,下拉列表中出现了 defaultRegionValue ",但我希望它作为DataTextValue.

The problem with my code above is that "defaultRegionValue" is coming in the dropdownlist as the DataTextField yet i want it as the DataTextValue.

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

I don't want to display the real string value in variable "defaultRegionValue", instead i want the dropdownlist to read it as selectedValue but then display i'ts corresponding text value.

此刻为显示值,所选值为空.如何正确设置?

At the moment is the displayed value and the selected value is null. How do i set this up correctly?

下面是我的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);
        }
    }

推荐答案

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

Set SelectedRionName equal to your cookie value, instead of declaring the 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")
 }

这篇关于如何设置Html.DropDownListFor的默认选定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆