简体   繁体   中英

ASP.NET MVC 3 Server Side Validation Fails with Dropdown list collections in ViewModel

I have a view that is strongly typed to a view model which contains properties for data submitted via the form on the page, as well as collections used to populate my dropdown lists.

On post, I check if the model state is valid, if it is not I return the view but i am getting a null reference because the view model no longer contains the collection values for the drop downs.

Do I need to re-hydrate the dropdown collections of the viewmodel before returning the form view again?

Controller Method:

[HttpPost]
    public ActionResult Create(UserProfileCreateViewModel viewModel)
    {
        if (ModelState.IsValid)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        return View();
    }

Yes, you have to. Http is a stateless protocol and ASP.NET MVC does not have a notion of postback or view state.

You should recreate the proper objects and send them back if ModelState.IsValid is set to false .

Yes, you need to rehydrate. The only thing bound to your model is what is submitted in the form post. So you might get the value of the selected item from a dropdown list, but not the whole dropdownlist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM