Take the 2-minute tour ×

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

share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

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.

share|improve this answer
Ahh, thank you! ViewBag.PropertyId was causing a collision with the select list named PropertyId. Confusing because it's the default scaffolding. Thank you very much. –  user1521567 Jan 30 '13 at 21:06
been there too. Great first post. Even better when you give code examples. –  Dave A Jan 30 '13 at 21:37
add comment

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);
share|improve this answer
add comment

Your Answer


