How to keep dropdownlist selected value after postback

后端 未结 6 1188
日久生厌
日久生厌 2020-12-19 13:03

In asp.net mvc3 how to keep dropdown list selected item after postback.

6条回答
  •  误落风尘
    2020-12-19 13:18

    MVC does not use ViewState, which means you will need to manage the value persistence yourself. Typically this is done through your model. So, given that you have a view model, e.g.:

    public class MyViewModel { }
    

    And your controller:

    public class MyController : Controller 
    {
        public ActionResult Something()
        {
            return View(new MyViewModel());
        }
    
        public ActionResult Something(MyViewModel model)
        {
            if (!ModelState.IsValid)
                return View(model);
    
            return RedirectToAction("Index");
        }
    }
    

    Now, when you pass the model back to the view with data (probably incorrect - failed validation), when you use your DropDownListFor method, just pass in the value:

    @Model.DropDownListFor(m => m.Whatever, new SelectList(...))
    

    ... etc.

    MVC's model binding will take care of the reading of the data into your model, you just need to ensure you pass that back to the view to show the same value again.

提交回复
热议问题