0

I have a single razor view in which i am trying to implement both Create and Edit options. Here is cshtml code for a drop down field:

@Html.DropDownListFor(model => model.StateID, (SelectList)ViewBag.StateID, "--Select--", new { @Id = "ddlState" })

However in edit mode although all the other fields are populated as per the model, the dropdown is not showing the saved selected value as per the model. I have used a viewbag to populate the dropdown and that works fine. The states are populated in the dropdown.

ViewBag.StateID = new SelectList(queryStatesInLookup, "LookupID", "LookupCode")

I debugged the razor page and checked. I get the state id from the model (for eg: 8), but this value wont bind to the dropdown. What gives? :/

1
  • on the drop down list for the selected value is set based on the lambda expression. So if you set StateID on the controller the selected value will be set Commented Apr 9, 2014 at 20:35

2 Answers 2

1

Apparently the Viewbag cannot have the same name as the property the model ID is bound to. My guess is the CLR is unable to resolve the conflicting names of the dynamic object type Viewbag and the model property name at run time. Thanks :)

Sign up to request clarification or add additional context in comments.

Comments

0

When you create your SelectList, you need to pass in the selected value there.

In the example below, replace SelectedValue with your actual selected value.

ViewBag.StateID = new SelectList(queryStatesInLookup, "LookupID", "LookupCode", SelectedValue)

1 Comment

Apparently the problem is that i gave the Viewbag the same name as the property name the model refers to. Its is an inconspicuous error to detect :/. Thanks for the effort though :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.