Html.DropDownList selected value does not work whe

2019-08-29 23:04发布

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

2条回答
一夜七次
2楼-- · 2019-08-29 23:48

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);
查看更多
贪生不怕死
3楼-- · 2019-08-29 23:49

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.

查看更多
登录 后发表回答