asp.net的MVC控制器后的最佳实践 [英] asp.net mvc controller post best practices

查看:115
本文介绍了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.

这篇关于asp.net的MVC控制器后的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆