C# 如何设置Html.DropDownListFor的默认选定值
我的视图中有上面的示例,它应该用区域列表填充Dropdownlist。选择一个区域后,我将该区域设置为cookie中的默认区域 下次他们访问应用程序时,我将检索cookie值,这样我就可以在变量“defaultRegionValue”中预先选择与我的cookie值匹配的区域(在下拉列表中) 我上面代码的问题是“defaultRegionValue”作为DataTextField出现在dropdownlist中,但我希望它作为DataTextValue 我不想在变量“defaultRegionValue”中显示真正的字符串值,而是希望dropdownlist将其作为selectedValue读取,然后显示其相应的文本值 此时为显示值,所选值为空。如何正确设置此项 下面是我的地区列表定义C# 如何设置Html.DropDownListFor的默认选定值,c#,asp.net-mvc,asp.net-mvc-4,html.dropdownlistfor,C#,Asp.net Mvc,Asp.net Mvc 4,Html.dropdownlistfor,我的视图中有上面的示例,它应该用区域列表填充Dropdownlist。选择一个区域后,我将该区域设置为cookie中的默认区域 下次他们访问应用程序时,我将检索cookie值,这样我就可以在变量“defaultRegionValue”中预先选择与我的cookie值匹配的区域(在下拉列表中) 我上面代码的问题是“defaultRegionValue”作为DataTextField出现在dropdownlist中,但我希望它作为DataTextValue 我不想在变量“defaultRegionVa
@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")
}
公共选择列表区域列表
{
得到
{
Dictionary items=this.qryRegionList.ToDictionary(k=>k.RegionName,v=>v.RegionID);
返回新的SelectList(items.OrderBy(k=>k.Key)、myConstants.Value、myConstants.Key);
}
}
将SelectedRoonName设置为cookie值,而不是声明defaultRegionValue
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);
}
}
将SelectedRoonName设置为cookie值,而不是声明defaultRegionValue
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
有一个构造函数重载,该重载接受参数中的选定值
您可以创建新的选择列表,如下所示:
@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")
}
SelectList
有一个构造函数重载,该重载接受参数中的选定值
您可以创建新的选择列表,如下所示:
@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")
}
地区列表的类型是什么?@EhsanSajjad它是一个选择列表Pynt和Ehsan Sajjad答案都有效,希望我能全部接受!地区列表的类型是什么?@EhsanSajjad它是一个选择列表Pynt和Ehsan Sajjad答案都有效,希望我能全部接受!