ASP.NET MVC dropdownlist not selecting value on render

前端 未结 8 635
感动是毒
感动是毒 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<SelectListItem> YearsCycling { get; set; }
    }
    

    Controller:

    var YearsCycling = new SelectList(new List<SelectListItem>() 
    { 
        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) %>
    
    0 讨论(0)
  • 2020-12-29 13:40

    Also Html.DropDownListFor uses values from POST request.

    Therefore if you have the same parameter in POST data MVC will use it even if you have different value in model.

    Check if you have the same name in request and change it.

    0 讨论(0)
提交回复
热议问题