步骤10:接下来,我们为应用增加编辑功能。同样,在edit()方法中鼠标右键,在弹出的菜单中选择增加视图,出现如下界面:

同样,这里记得选择Scaffold脚手架模版为Edit,然后修改edit代码如下:
public ActionResult Edit(int id)
{
using (var databaseContext = new Models.MyDataContext())
{
return View(databaseContext.Customer.Find(id));
}
}
{
using (var databaseContext = new Models.MyDataContext())
{
return View(databaseContext.Customer.Find(id));
}
}
这里首先是根据前端列表用户选择的id,在数据库中根据id找出相应的customer实体类,然后再传递给前端页面视图。
接下来,就是当用户编辑好数据后,提交后的更新处理部分,代码如下:
[HttpPost]
public ActionResult Edit(int id, Models.Customer customer)
{
try
{
using (var databaseContext = new Models.MyDataContext())
{
databaseContext.Entry(customer).State= System.Data.EntityState.Modified;
databaseContext.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
public ActionResult Edit(int id, Models.Customer customer)
{
try
{
using (var databaseContext = new Models.MyDataContext())
{
databaseContext.Entry(customer).State= System.Data.EntityState.Modified;
databaseContext.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
其中,在修改更新数据时,只需要设置databaseContext.Entry(customer)的state状态为System.Data.EntityState.Modified,即表示数据是已修改的,最后在用savechanges方法保存到数据库。