简体   繁体   中英

An unhandled exception occurred during the execution of the current web request. Model compatibility cannot be checked

An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

public class HomeController : Controller
{
    [HttpGet]
    [ActionName("Registration")]
    public ActionResult Registration_Get()
    {
        //Contry();
        return View();
    }

    [HttpPost]
    [ActionName("Registration")]
    public ActionResult Registration_Post()
    {
        Registration register = new Registration();
        TryUpdateModel(register);

        if (ModelState.IsValid)
        {
            AddStudent(register);

            return RedirectToAction("Registration");
        }

        return View(register);
    }

    public ActionResult AddStudent(Registration r)
    {
        OQContext db = new OQContext();
        db.Registrations.Add(r);
        db.SaveChanges();
        return View();
    }

}

I want to save form data to database table but an exception occure in AddStudent action method on db.Registrations.Add(r);

Change your controller to

[HttpGet]
[ActionName("Registration")]
public ActionResult Registration_Get()
{
    //Contry();
    return View();
} 

[HttpPost]
[ActionName("Registration")]
public ActionResult Registration_Post(Registration r)
{
    //This needs to come from the view
    //Registration register = new Registration();
    //TryUpdateModel(r);

    if (ModelState.IsValid)
    {
        AddStudent(r);

        return RedirectToAction("Registration");
    }

    return View(r);
}

You are not yet passing the model from the view

Change controller methods like this :

   public ActionResult AddStudent()
   {
        return View();
   }

   [HttpPost]
   public ActionResult AddStudent(Registration r)
   {
     try
     {
      OQContext db = new OQContext();
       db.Registrations.Add(r);
       db.SaveChanges();
     }
     catch(Exception ex)
     {
     }
     return View();
   }

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