HTML.DropDownList does not respect pre-selected value

I want to use Html.DropDownList (string name, IEnumerable SelectList, Object htmlAttributes) to display a select list with a pre-selected value for me.

My picklist is in the model object of my view, so I wrote the following code:

<%= Html.DropDownList("aName", mySelectList, new { }) %>

A selection list will be displayed without a pre-selected value.

The workaround I found is to pass the SelectList as ViewData and do the following:

In the controller:

ViewData["TimeZones"] = mySelectList;

In view:

<%= Html.DropDownList("TimeZones", null, new { }) %> 

This way the selection list will be displayed with a preselected value, however I do not want me to have to pass my selection list as presentation data. What am I doing wrong? Thanks in advance for your help.

+3
3

( ):

<%: Html.DropDownList("DropdownName", new SelectList(ListItems, "Value", "Text", selectedItem), htmlAttributes)%>

, .

+3

DropDownList.

, , true Selected . , .

var model = new IndexViewModel()
            {
                ListItems = items,
                SelectedItem = 2
            };

, , , selectList:

<%= Html.DropDownList("SelectedItem", Model.ListItems) %>

HTML , HTML ListItems, - SelectedItem.

, , , , , .

+1

, , MVC5. , - , .

VS DropDownLists :

@Html.DropDownList("EpisodeTypeId", null, htmlAttributes: new { @class = "form-control" })

VS ViewBag - Create vs. and Edit.

create:

ViewBag.EpisodeTypeId = new SelectList(db.EpisodeTypes, "Id", "Name");

:

ViewBag.EpisodeTypeId = new SelectList(db.EpisodeTypes, "Id", "Name", episode.EpisodeTypeId);

Edits, . , DropDown.

Automatically generated VS code will be correct, but if you add the fields manually later, it's easy to skip.

0
source

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


All Articles