Html.DropDownList selected value does not work when i specify the name

二次信任 提交于 2020-01-07 05:59:18

问题


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);


来源:https://stackoverflow.com/questions/14613213/html-dropdownlist-selected-value-does-not-work-when-i-specify-the-name

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