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 a SelectList
object in the ViewModel
, I tried it something like this
In my ViewModel
I used a property of type SelectList
like this
SelectList HoursToSelect = new SelectList(MyDictionaryObject, "Value", "Key", 14/*selected value*/);
and I was using it like this
@Html.DropDownListFor(m => m.EndsOnHour, HoursToSelect)
This all was working fine and fulfilled my requirement completely
But the problem is due to my project's architecture I cannot use SelectList
object in my ViewModel
as my project does not allow non serializable classe in the ViewModel
.
So the only way left for me is to have something in my View only, something here
@Html.DropDownListFor(m => m.EndsOnHour, new SelectList(Model.Hours, "Value", "Key"))
But don't know what! Anybody have idea to achieve this?
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 SelectListItem
s 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.