【问题标题】:An unhandled exception occurred during the execution of the current web request. Model compatibility cannot be checked当前 Web 请求执行期间发生未处理的异常。无法检查模型兼容性
【发布时间】:2019-06-21 14:00:28
【问题描述】:

在执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

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();
    }

}

我想将表单数据保存到数据库表中,但在 db.Registrations.Add(r) 上的 AddStudent 操作方法中出现异常;

【问题讨论】:

  • 处理异常以便识别错误。使用 try/catch 块捕获异常并检查它,它试图告诉您问题所在。
  • 调试程序并检查异常、内部异常以及堆栈跟踪。这应该可以帮助您找出问题所在。在此处发布完整的异常信息也将允许我们帮助您。
  • 查看上面的代码,错误出现在 db.savechanges(); 上。错误详细信息是:System.ComponentModel.Win32Exception:系统找不到指定的文件
  • 错误已解决,存在与数据库相关的问题,我已通过将 server=.; 更改为 server=BeCool\SQLEXPRESS; 在连接字符串中

标签: c# asp.net-mvc


【解决方案1】:

将您的控制器更改为

[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);
}

你还没有从视图中传递模型

【讨论】:

  • 现在错误是 system.data.entity.infrastructure.dbupdateexception'发生在 entityframework.dll
  • 您是在更新还是保存数据?还要确保您的主键是自动递增的。显示堆栈跟踪或在此处查看更多详细信息stackoverflow.com/questions/19424058/…
  • 我正在尝试保存数据@Bosco
  • 哪一行会抛出这个错误。错误说更新。你看我发的链接了吗?
【解决方案2】:

像这样更改控制器方法:

   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();
   }

【讨论】:

  • 所以他应该吞下错误,让用户认为一切正常?
  • 我怀疑 OP 想要解决错误,而不是忽略它。
猜你喜欢
  • 1970-01-01
  • 2014-04-21
  • 2016-04-25
  • 1970-01-01
  • 2020-06-09
  • 1970-01-01
  • 2022-01-17
  • 2015-12-14
  • 1970-01-01
相关资源
最近更新 更多