ASP.NET MVC dropdownlist not selecting value on render

前端 未结 8 779
感动是毒
感动是毒 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:18

    Binding dropdownlist is very tricky in MVC it embarrassed me a lot you can do it with this in your controller get all your cities list put it in viewBag

    Create

          ViewBag.CityId = new SelectList(db.Cities, "ID", "Name");
    

    user.CityID if you are in Edit so that on edit it select the city

          ViewBag.CityId = new SelectList(db.Cities, "ID", "Name", user.CityID);
    

    in your View just do this trick

         @Html.DropDownList("CityId", "Select")
    

    this is the most simplest way I know....

提交回复
热议问题