我需要更新模型视图并在数据库

时间:2016-11-10 07:50:23

标签: asp.net-mvc-4 linq-to-sql model

在这里,我有一个强类型视图,其中我以一种形式向注册用户显示他/她的数据,这将允许更新编辑数据并将这些更改反映回数据库。

我已经相应地在GET和POST方法中编写了动作方法的所有代码,但我无法弄清楚是什么导致了这个问题。问题是我在视图页面上做的更改绑定到了模型类虽然我已经编写了db.submit changes()方法,但没有反映回数据库表。

以下是我的代码: Detailsupdate视图页面的GET和POST操作方法:

    [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult PatientDetailsPage2(Patients p)
        {
            if (ModelState.IsValid)
            {
                tblPatient updatedpatientdetail = new tblPatient()
                {
                    PatientName = p.PatientName,
                    PatientAge = (short) p.Age,
                    PatientMail = p.PatientEmail,
                    PatientMobileNo = p.PatientMobileNo,
                    PatientPassword = p.PatientPassword
                };
                db.SubmitChanges();
                return View();
            }
            else
            {
                ViewBag.ErrorMessage = "Please ensure all the fields are filled correctly";
            }
            return View();

        }
        public ActionResult PatientDetailsPage2()
        {
            if(TempData["doc"] != null)
            {
                var data = (Patients)TempData["doc"];
                return View(data);
            }
            return View();
        }

另外我要提一下,当我调试并扫描更新的值时,它会在模型​​的对象被分配到表参数的位置显示更新的值,但是一旦提交更改行代码被扫描,它就会显示旧的密码字段的值(我想在这里更新的字段值)。请帮助我程序员!

1 个答案:

答案 0 :(得分:0)

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult PatientDetailsPage2(Patients p)
    {
        if (ModelState.IsValid)
        {
            tblPatient updatedpatientdetail = new tblPatient()
            {
                PatientName = p.PatientName,
                PatientAge = (short) p.Age,
                PatientMail = p.PatientEmail,
                PatientMobileNo = p.PatientMobileNo,
                PatientPassword = p.PatientPassword
            };
            db.Patients.Add(updatedpatientdetail);
            db.SubmitChanges();
            return View();
        }
        else
        {
            ViewBag.ErrorMessage = "Please ensure all the fields are filled correctly";
        }
        return View();

    }

您必须在保存之前将模型对象添加到Db模型。

相关问题