asp.net mvc控制器发布最佳实践

Men*_*ion 2 asp.net-mvc controller asp.net-mvc-3

我对使用问题的"最佳实践"控制器感到有点困惑.

我典型的代码看起来

    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");                
        }
Run Code Online (Sandbox Code Playgroud)

好吧,最好使用"TryUpdateModel"或仅使用"UpdateModel"或简单调用Model.IsValid并且最好在控制器中捕获异常?

谢谢

Dar*_*rov 5

这是我更喜欢的替代方式:

[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");
}
Run Code Online (Sandbox Code Playgroud)

所以,你可以看到不FormCollection,不TryUpdateModel,不UpdateModel,不try/catch.