How to set default selected value for Html.DropDownListFor

你说的曾经没有我的故事 提交于 2019-12-25 05:31:35

问题


    @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")
     }

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.

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".

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

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?

And below is my RegionList definition

 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);
        }
    }

回答1:


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")
 }



回答2:


SelectList has a constructor overload which takes selected value in parameters.

you can create new SelectList like this:

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


来源:https://stackoverflow.com/questions/29540793/how-to-set-default-selected-value-for-html-dropdownlistfor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!