Html.DropDownList selected value does not work whe

2019-08-29 23:23发布

问题:

I am trying to select a specific option from a dropdown list when the page is rendered.

On my Controller I have this code:
ViewBag.PropertyId = new SelectList(db.Properties, "PropertyId", "PropertyName", id.ToString());

On my view, This does not work. The selected option is the first option always.
@Html.DropDownList("PropertyId", (SelectList)ViewBag.PropertyId)

This does work on my view, the correct option is selected. However, I can not save this because I need the name of the select list to be PropertyId, so that it is posted correctly.
@Html.DropDownList("sadgfsadsaf", (SelectList)ViewBag.PropertyId)

Can someone please help me understand what i should be doing here? I understand i should use a viewmodel instead of Viewbag but I just want get this working first.

Thank you

回答1:

I've had this same issue before and it was a name collision. Try changing your dropdown and/or value name and see what happens.



回答2:

A name collision might also happen when you do a post back to the same controller & view again, but want to change the state in the controller.

It will keep the posted model state in the ModelState object and restore the posted state in the rendered view. In order to change the model state in the controller you will have to perform ModelState.Remove("PropertyId") or set it immediately:

ModelState["PropertyId"].Value = new System.Web.Mvc.ValueProviderResult(id.ToString(), id.ToString(), System.Globalization.CultureInfo.CurrentCulture);