Selected value in the asp.net MVC 4.0 drop-down list

I am trying to create a dropdown using the DropdownListFor function and I want a value to be selected in it.

I searched a lot and found a similar kind of solution with a SelectList object in ViewModel , I tried 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 used it like that

 @Html.DropDownListFor(m => m.EndsOnHour, HoursToSelect) 

All this worked perfectly and fully complied with my requirement.

But the problem is with my project architecture. I cannot use the SelectList object in my ViewModel , since my project does not allow non-serializable splitting in the ViewModel .

Thus, the only way left for me is something in my mind, something here.

  @Html.DropDownListFor(m => m.EndsOnHour, new SelectList(Model.Hours, "Value", "Key")) 

But I don’t know what! Anyone have an idea to achieve this?

+4
source share
2 answers

When you use @Html.DropDownListFor(...) with an object property, it will use the current state of the object to set the selected item. Therefore, in your example, if you do not specify a value in the select list, it will use the value of m.EndsOnHour to set the selected value. In fact, the select list does not even have to be a SelectList for each user, it really needs to be a set of SelectListItem , as you can see in the documentation .

However, the problem with serialization still exists. You have a couple of options, the easiest of which is to simply throw away the values ​​on the view side, if possible. Many drop-down lists are created for static selection to display possible enumeration options, such as, for example, listing states or countries. Other common examples are date ranges, etc. In these cases, you can write helpers that will generate these lists and call them in your view, and then simply remove them from your view model.

If the list is dynamic, in the long run it does not work very well and is likely to cause additional communication, which will negatively affect the maintenance of your system. In this case, you will need to create your own child class SelectList , which is serialized, and then use it as a parameter of the type type of the serializable implementation of IEnumerable<T> . Arrays in C # are serializable, so you need this part.

+4
source

Personally, I gave up with DropDownListFor and just did something like this ... It's a lot easier. Not sure if there is 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> 
+3
source

Source: https://habr.com/ru/post/1391852/


All Articles