2016-11-10 22 views
0

在这里,我有一个强类型视图,在该视图中,我向注册用户显示了他/她的数据,以允许更新编辑数据并使这些数据更新变化反映回数据库。我需要更新模型视图并反映数据库中的这些更改

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

下面是我的代码:

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

另外我想提的是,当我把调试和扫描更新的值也显示:对于Detailsupdate视图页面 GET和POST操作方法在模型对象被分配到表格参数中的点处的更新值,但是一旦提交更改行代码被扫描,它就会显示旧密码字段的值(我想在此更新的字段值)。请帮助我的程序员!

+0

您需要在保存之前将'tblPatient'添加到上下文中 - 例如, 'db.Patients.Add(tblPatient); db.SaveChanges();' –

+0

@StephenMuecke患者是一个模型类,它在代码中根本没有加载 –

+0

对不起,应该是'updatedpatientdetail',而不是'tblPatient' –

回答

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模型。

相关问题