Skip to content Skip to sidebar Skip to footer

Selected Value In Asp.net MVC 4.0 Dropdownlist

I am trying to make a dropdown list using DropdownListFor function and I want to have a value selected in it. I have searched a lot and found the similar kind of solution of having

Solution 1:

When you use @Html.DropDownListFor(...) with a property of an object, it will use the current state of the object to set the selected item. So in your example, if you don't specify the value in the select list, it would use the value of the m.EndsOnHour to set the selected value. In fact, the select list doesn't even really have to be a SelectList per say, it really just needs to be a collection of SelectListItems as you can see in the documentation.

Your problem of serialization still exists however. You have a couple options here, the easiest of which is to just throw the values on the view side, if that's possible. Many drop down lists are built for static choices to display possible selections of an enumeration, like listing off states or countries for instance. Other common examples are for date ranges, etc. In these instances, you can write helpers that will generate those lists and call them in your view, then just remove them from your view model.

If the list is dynamic however, this won't work very well in the long run and will likely cause extra coupling that will have a negative effect on the maintenance of your system. In this case you will need to create your own SelectList child class that is serializable and then use that as the generic type parameter of a serializable implementation of IEnumerable<T>. Arrays in C# are serializable, so you that part is taken care of.


Solution 2:

Personally I gave up with the DropDownListFor and just did something like this.... Its much simpler. Not sure if there's any reason why this would not be a good idea.

<select id="details-title">
@foreach (var title in Helper.Titles)
{
<option value="@title.Value" @(title.Value==Model.SelectedTitle?"selected=\"selected\" ":"")>@title.Text</option>
}
</select>

Post a Comment for "Selected Value In Asp.net MVC 4.0 Dropdownlist"