asp.net的MVC控制器后的最佳实践

问题描述:

我对最佳实践控制器使用的问题有点糊涂了。

I am bit confused about "best practice" controller using question.

我通常code看看

    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并捕捉例外控制器好主意吗?

Well, is better using "TryUpdateModel" or only "UpdateModel" or simple call Model.IsValid and is good idea to catch exception in controller?

感谢

如果您希望和计划,以应付例外这取决于

This depends if you expect and plan to deal with exceptions.

我通常的做法是:

public ActionResult foobar(FormCollection formCollection)
{
    //Keep this out of the try catch scope in case you need to pass it
    // to the next method.
    Model model = new Model();

    try
    {
        if(!TryUpdateModel(model)
        {
            //Update Failed so fix it and redirect
            return redirectToAction("fixit");
        }
        if(!ModelState.IsValid())
        {
            //Update worked but model state was invalid, return to page to correct 
            //model validation errors
            return View("foobar", model);
        }
        //Update Succeeded so do other stuff
    }
    catch(Exception ex)
    {
        //Deal with Exception
        return redirectToAction("ErrorView", "ErrorController");
    }

    return redirectToAction("NextStep");
}

我尝试用所有的人都在我的code,试图抓住每一个问题,它打破了之前的东西。

I try to use all of them in my code to try and catch every issue before it breaks something.