ASP.NET MVC dropdownlist not selecting value on render

前端 未结 8 729
感动是毒
感动是毒 2020-12-29 12:56

I have this annoying problem where my DropDownlist doesn\'t select the current value by default.

Controller:

var YearsCycling = new SelectList(new Li         


        
8条回答
  •  [愿得一人]
    2020-12-29 13:35

    Try this:

    Create a viewmodel:

    public class MyViewModel
    {
        public string SelectedValue { get; set; }
        public IEnumerable YearsCycling { get; set; }
    }
    

    Controller:

    var YearsCycling = new SelectList(new List() 
    { 
        new SelectListItem(){ Value="1yr", Text="1yr"},
        new SelectListItem(){ Value="1-3yrs", Text="1-3yrs"}, 
        new SelectListItem(){ Value="3-5yrs", Text="3-5yrs"}, 
        new SelectListItem(){ Value="5-10yrs", Text="5-10yrs"}, 
        new SelectListItem(){ Value="10+yrs", Text="10+yrs"} 
    },
    "Value",
    "Text");
    
    MyViewModel model = new MyViewModel();
    model.YearsCycling = YearsCycling;
    model.SelectedValue = "5-10yrs";
    return View(model);
    

    View:

    <%:Html.DropDownListFor(model=>model.SelectedValue,(SelectList)Model.YearsCycling) %>
    

提交回复
热议问题