[英]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.