Pass SelectList “SelectedValue” to Controller Action Method

人走茶凉 提交于 2019-12-01 10:57:21

The RegistrationViewModel type should contain a simple-typed property such as:

public string DivisionValue { get; set; }

Or change the type to int, DateTime, or whatever the appropriate type is.

In HTML and HTTP the only thing that gets posted back for a drop down list is the name of the field and the selected value.

To get everything to match up you also need to change the view to render a different input name for the drop down list:

<%= Html.DropDownList("DivisionValue", ViewData["DivisionList"] as SelectList)%>

Notice that I'm using "DivisionValue" is the value of the list, and DivisionList as the list of all available items.

I'd just be more explicit with the SelectList type. I'd suggest creating the SelectList in the controller action and forget about casting it in the view. My code works like this (CRUD Edit page):

..in the Action:

            ViewData["WorkType.ID"] = new SelectList(this._vacancySvc.GetVacancyWorkTypes(),
            "ID", "Name", ViewData["WorkType.ID"] ?? vacancy.WorkType.ID);

..and in the view:

<p><% =Html.Encode("Work Type:") %><br />
            <% =Html.DropDownList("Worktype.ID")%><span class="smallgrey">(required)</span><br />

.. you can see that either the initial selection (from DB) is persisted or the ViewData from post backs (like if the form fails validation) thru the use of the [null coalescing operator][1] (??).

Moreover, if i refactored this code, i'd prob like to use a ViewModel object like you are. The only thing is: (1) you'd never need to reference the ViewModel SelectList property in the view coz MVC auto binds this for us by the Html.DropDownList() overload.. and (2) i'd still need to ref the ViewData in the action anyway to get the selected value from a failed validation post back so what's the point really??

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!