MVC - Set selected value of SelectList

后端 未结 14 1206
后悔当初
后悔当初 2020-12-13 08:03

How can I set the selectedvalue property of a SelectList after it was instantiated without a selectedvalue;

SelectList selectList = new SelectList(items, \"I         


        
14条回答
  •  余生分开走
    2020-12-13 08:48

    Simply use the third parameter for selected value in mvc4

    @Html.DropDownList("CountryList", new SelectList(ViewBag.Countries, "Value", "Text","974"))
    

    Here "974" is selected Value Specified

    In my result selected country is now qatar.in C# as below`

        foreach (CountryModel item in CountryModel.GetCountryList())
            {
                if (item.CountryPhoneCode.Trim() != "974")
                {
                    countries.Add(new SelectListItem { Text = item.CountryName + " +(" + item.CountryPhoneCode + ")", Value = item.CountryPhoneCode });
    
                }
                else {
    
    
                    countries.Add(new SelectListItem { Text = item.CountryName + " +(" + item.CountryPhoneCode + ")", Value = item.CountryPhoneCode,Selected=true });
    
                }
            }
    

提交回复
热议问题