Dropdownlistfor will not show the correct selection

前端 未结 2 924
执念已碎
执念已碎 2020-12-02 01:49

I have three dropdownlistfor in a loop that do not show the correct value from the DB. They always default to the first entry. I have checked and double checked the DB and

2条回答
  •  旧时难觅i
    2020-12-02 02:23

    If you want to set the selected value that is coming in Model. You need to do it like this:

    @Html.DropDownListFor(m => oProfile.BodyTypeShoulderId, 
                               new SelectList(Model.BodyTypeShoulders, 
                                              "Id", 
                                              "Name",
                                              oProfile.BodyTypeShoulderId), 
                               new { @class = "form-control input-sm-select" })
    

    The above code will set the dropdown selected value to whatever is in the current Model object BodyTypeShoulderId

    The first argument of DropDownListFor tells that on form post drop down selected value will be mapped with the Model property which is set there (we are passing m => oProfile.BodyTypeShoulderId) but this not sets selected Value.

    For setting selected value you have to pass SelectList fourth parameter using this overload of SelectList class which is object selectedValue

提交回复
热议问题