SelectListItem selected = true not working in view

前端 未结 6 2013
醉酒成梦
醉酒成梦 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:19

    I suggest it's better if you use strongly typed property for SelectList (rather than using ViewBag/ViewData). I believe what you are expecting is that your dropdownlist to be pre-selected with the gender selection made in the model. Here is a solution (code is not 100% clean. But this will work)

    Model

    public class TestModel
    {
        public string Gender { get; set; }
    
        public IEnumerable GenderList
        {
            get
            {
                List list = new List { new SelectListItem() { Text = "Select", Value = "Select" }, new SelectListItem() { Text = "Male", Value = "Male" }, new SelectListItem() { Text = "Female", Value = "Female" } };
                return list.Select(l => new SelectListItem { Selected = (l.Value == Gender), Text = l.Text, Value = l.Value });
            }
        }
    }
    

    Controller Action

    public ActionResult MyView()
    {
        TestModel m = new TestModel();
        m.Gender = "Female";
        return View(m);
    }
    

    MyView.cshtml

    @model TestModel
    
    @{
        ViewBag.Title = "MyView";
    }
    
    

    MyView

    @using (Html.BeginForm()) {
    @Html.DropDownListFor(model => model.Gender, Model.GenderList)
    }

    OUTPUT

    dropdown with 'Female' option selected

    enter image description here

    EDIT

    Based on comments find below links to sample projects

    1) https://github.com/prashanth-t/DropdownDemo_BareBones (Using the MVC 4 empty template. Smaller file size with bare minimum)

    2) https://github.com/prashanth-t/DropdownDemo (Using the MVC 4 internet application template. Bigger file size)

提交回复
热议问题