简体   繁体   English

MVC空异常

[英]MVC null exception

I am making my MVC application. 我正在制作我的MVC应用程序。 One view includes a form. 一个视图包括一个表单。 After filling it, the form is validated and if model is valid, then it should move to another window, but if not, nothing should happen, but apparently, some of the data is lost then. 填写表单后,将对表单进行验证,如果模型有效,则应将其移至另一个窗口,但如果没有,则什么也不会发生,但是显然会丢失一些数据。 My controller: 我的控制器:

  public ActionResult PickGroupForHomework(PickGroupForHomeworkViewModel model)
        {
            ClassDeclarationsDBEntities2 entities = new ClassDeclarationsDBEntities2();
            model.groups = entities.Groups.ToList();
            model.users = entities.Users.ToList();
            int id = model.subject_id;
            var subj = entities.Subjects
                    .Where(b => b.class_id == id)
                    .FirstOrDefault();
            model.subject_name = subj.name;
            if (ModelState.IsValid)
            {

            }
            else
            {

                if (subj != null)
                {
                    model.subject_name = subj.name;
                }
                model.subject_id = model.subject_id;
                model.groups = entities.Groups.ToList();
                model.users = entities.Users.ToList();
                return View(model);
            }
            return View(model);

        }

And apparently subject_id and qty is null after false validation. 在错误验证之后, subject_idqty显然为null。 Why? 为什么?

Do you have in the view, a field or hidden field binding to the Subject_Id property from your model? 在视图中,您是否有绑定到模型中Subject_Id属性的字段或隐藏字段? If you don't have at least a hidden field that binds to a property from a model in a strongly typed view, this data will be lost when your user posts the form and your controller is called. 如果您没有至少一个绑定到强类型视图中模型属性的隐藏字段,则当用户发布表单并调用控制器时,此数据将丢失。

@Html.HiddenFor(m => m.Subject_Id)

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

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