MVC3: Set Dropdown list Selected Value

2019-05-02 08:55发布

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?

2条回答
贼婆χ
2楼-- · 2019-05-02 09:30

Just do:

@Html.DropDownListFor(m => m.State, new SelectList(Model.StateList, "Value", "Text", Model.State))
查看更多
冷血范
3楼-- · 2019-05-02 09:36

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))
查看更多
登录 后发表回答