我对使用问题的“最佳实践” Controller 有点困惑。
我通常的代码外观
public ActionResult Edit(int reportId,FormCollection formCollection)
{
try
{
var report = _dbContext.EmployeeReports.Find(reportId);
if (TryUpdateModel(report))
{
_employeeReportService.Update(report);
return RedirectToAction("List");
}
return View("Edit", report);
}
catch (Exception)
{
// some logging etc
return RedirectToAction("List");
}
那么,使用“TryUpdateModel”或仅使用“UpdateModel”或简单调用 Model.IsValid 更好,并且是在 Controller 中捕获异常的好主意吗?
谢谢
最佳答案
这是我更喜欢的另一种方式:
[HttpPost]
public ActionResult Edit(ReportViewModel reportViewModel)
{
if (!ModelState.IsValid)
{
// there were validation errors => redisplay the form
// so that the user can fix them
return View(reportViewModel);
}
// At this stage the view model is valid => we can
// map it back to a domain model and pass to the repository
// for processing
// Fetch the domain model that we want to update
var report = _repository.Get(reportViewModel.Id);
// map the domain model properties from the view model properties
// in this example I use AutoMapper
Mapper.Map<ReportViewModel, Report>(reportViewModel, report);
// perform update
_repository.Update(report);
// the update wen fine => we can redirect back to the list action
return RedirectToAction("List");
}
因此,正如您所看到的,没有 FormCollection
、没有 TryUpdateModel
、没有 UpdateModel
、没有 try/catch
.
关于asp.net-mvc - asp.net mvc Controller 帖子最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7474343/