[英]How to update the domain model object based on the domain model parameter passed to Edit action method?
我有一个操作方法来处理HTTP-POST,如下所示。
[HttpPost]
public ActionResult Edit(Movie model)
{
var movie = db.Movies.FirstOrDefault(x => x.Id == model.Id);
if (movie == null)
{
TempData["MESSAGE"] = "No movie with id = " + id + ".";
return RedirectToAction("Index", "Home");
}
if (!ModelState.IsValid)
return View(model);
// what method do I have to invoke here
// to update the movie object based on the model parameter?
db.SaveChanges();
return RedirectToAction("Index");
}
问题:如何基于model
更新movie
?
编辑1
基于@lukled的解决方案,这是最终的工作代码:
[HttpPost]
public ActionResult Edit(Movie model)
{
var movie = db.Movies.FirstOrDefault(x => x.Id == model.Id);
if (movie == null)
{
TempData["MESSAGE"] = string.Format("There is no Movie with id = {0}.", movie.Id);
return RedirectToAction("Index", "Home");
}
if (!ModelState.IsValid)
return View(model);
var entry = db.Entry(movie);
entry.CurrentValues.SetValues(model);
db.SaveChanges();
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult Edit(Movie movie)
{
if (movie == null)
{
TempData["MESSAGE"] = "No movie with id = " + id + ".";
return RedirectToAction("Index", "Home");
}
if (!ModelState.IsValid)
return View(movie);
// what method do I have to invoke here
// to update the movie object based on the model parameter?
db.Movie.AddObject(movie);
db.ObjectStateManager.ChangeObjectState(movie, System.Data.EntityState.Modified);
db.SaveChanges();
return RedirectToAction("Index");
}
尝试这个:
db.Movies.ApplyCurrentValues(model);
db.SaveChanges();
您也可以将值从模型复制到电影:
movie.Title = model.Title;
movie.Director = model.Director;
db.SaveChanges();
好。 您正在使用代码优先,因此可能是:
var entry = context.Entry(movie);
entry.CurrentValues.SetValues(model);
db.SaveChanges();
但是我不确定,因为我没有安装Code First。 取自:
你有没有尝试过
TryUpdateModel(movie)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.