MVC3: Set Dropdown list Selected Value
Asked Answered
M

2

5

I am using mvc3 and I have a drop down list in my view.

@Html.DropDownListFor(m => m.State,
new SelectList(Model.StateList, "Value", "Text"))

Is there a way of setting the selected value in the View?

Merlenemerlin answered 4/12, 2012 at 21:38 Comment(0)
L
6

Extending on what Romias said, in your controller, set Model.State to whatever value you want. If you wanted 'WI', then Model.State should equal that.

Controller:

public ActionResult Index()
{
    var m = new TestViewModel();
    m.State = "WI";
    return View(m);
}

View:

@Html.DropDownListFor(m => m.State, new SelectList(Model.StateList, "Value", "Text", Model.State))
Lovins answered 4/12, 2012 at 23:8 Comment(3)
Is it possible to set this value in the view instead?Merlenemerlin
It is, by why would you want to? It's bad practice.Lovins
Hi @rudeovski ze bear, It's works for me. thank you very much.Sometimes
H
1

Just do:

@Html.DropDownListFor(m => m.State, new SelectList(Model.StateList, "Value", "Text", Model.State))
Haroldson answered 4/12, 2012 at 21:49 Comment(1)
May be he meant "using javacript"... but lets wait for him to update the question or something.Haroldson

© 2022 - 2024 — McMap. All rights reserved.