简体   繁体   中英

MVC null exception

I am making my MVC application. 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. Why?

Do you have in the view, a field or hidden field binding to the Subject_Id property from your model? 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)

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