asp.net-mvc - asp.net mvc Controller 帖子最佳实践

标签 asp.net-mvc asp.net-mvc-3 controller

我对使用问题的“最佳实践” 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/

相关文章:

asp.net-mvc-3 - Paypal - 如何使用 PayPal 购买音频并在购买后立即下载文件

asp.net-mvc-3 - Html.RenderPartial 和 Ajax.BeginForm -> Submit 被调用两次

javascript - 如何正确地与另一个 Controller 管理的 View 交互?

grails - Controller 和请求参数之间的区别

routing - Rails Action Controller 中的未定义方法 `devise_for'

javascript - 对 Controller 的Web API调用不起作用,断点不起作用,先前版本的代码不再起作用(使用ANSWER更新)

jquery - MVC、WCF ASP.NET 4.0 和 JQUERY

jquery - 你知道为什么为我的下拉框引入 jquery ui 自动完成功能也会改变我的列表框吗?

asp.net-mvc - 由 linq 查询引起的 StackOverflowException

c# - 如何将 View 模型传递给布局/母版页?