简体   繁体   English

ASP.NET MVC 3服务器端验证因ViewModel中的下拉列表集合而失败

[英]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? 在再次返回表单视图之前,是否需要重新填充viewmodel的下拉列表集合?

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. Http是无状态协议,ASP.NET MVC没有回发或视图状态的概念。

You should recreate the proper objects and send them back if ModelState.IsValid is set to false . 如果ModelState.IsValid设置为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. 因此,您可能会从下拉列表中而不是整个下拉列表中获得所选项目的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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