SelectListItem selected = true not working in view

前端 未结 6 1920
醉酒成梦
醉酒成梦 2021-02-07 09:36

I have a gender select field (--Select--, Male, Female) and I\'m populating that in my controller. When the page loads, I want the gender that is selected in the model pm.

6条回答
  •  天涯浪人
    2021-02-07 10:25

    Try this instead in the controller:

    string[] gender = new string[] {"Male", "Female"};
    string selectedGender = gender.Where(x => x.StartsWith(pm.gender)).FirstOrDefault();
    ViewData["gender"] = new SelectList(gender, selectedGender);
    

    And in the view:

    <%: Html.Dropdownlist(x => x.Gender, ViewData["gender"], "Select") %>
    

提交回复
热议问题