Pregunta

Below is my code to create a drodownlist in mvc 4.0. Also, I am trying to set a selected value.

I can see my statesList has a value which is selected, But the dropdown never selects the selected value.

Dictionary<String,String> states = Model.State;
var statesList = new SelectList(states, "Value", "Key", Model.SelectedState.ToUpper());
@Html.DropDownListFor(l => l.State, statesList, new { @id = "ddlStates" })

My Model looks like below

public class ConsumerModel
{
    public Dictionary<string, string> State { get; set; }
    public String SelectedState { get; set; }
}
¿Fue útil?

Solución

I think you need:

@Html.DropDownListFor(l => l.SelectedState, statesList, new { @id = "ddlStates" })

The first parameter should be the property that holds the value in the model. Not the list. That is what you pass to the second parameter.

Otros consejos

drop down list for sets the selected value based on the model. Since you are setting the list on your view you don't need the state field. change your drop down list for to

@Html.DropDownListFor(l => l.SelectedState, statesList)

you can't override the id field on a for helper. and set SelectedState on the controller and it will set on the view.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top