-->

How to set default selected value for Html.DropDow

2019-09-04 01:32发布

问题:

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