Dropdown not displaying selected value in case of list of model

In this post I have described the problem and solution of the Dropdown not displaying selected value in case of list of model

Sometimes during programming we have some cases where we need to use list of model. There can be many examples like we need to save multiple user bank accounts or credit cards or we can take example of # of cars during policy creation process etc. So there can be many scenarios according to our business requirements.

How I can fix this?

You might noticed one thing that all input and other fields like textarea works very well they does show correct value what the user actually fill out but there is one problem like I said above all input and other fields works instead one field that is dropdown, you heard correct, dropdown.

I noticed all fields were displaying correct values what the user previously entered but the problem with dropdown was its was not displaying the selected value rather just behaving like user didn’t ever select the value but the interesting thing I noticed in the code behind, I take a look at the model object at the httppost method, I was getting the correct value but it was just not displaying on the page.

After researching this issue, eventually I came with this solution that was instead creating Selectlist from controller I have to create in on the cshtml page. This is the only trick which worked for me.

I don’t know why this issue was caused but this trick did his work, following is the code.

Solution

@Html.DropDownListFor(x => x.OrderStatusId, new SelectList(Model.OrderStatuses, "Id", "Name", Model.OrderStatusId), "-- Select --")

Leave a Reply