如何设置Html.DropDownListFor的默认选定值

编程入门 行业动态 更新时间:2024-10-27 10:30:31
本文介绍了如何设置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的默认选定值

本文发布于:2023-11-06 08:03:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563137.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何设置   Html   DropDownListFor

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!