Must ASP.NET MVC Controller Methods Return ActionResult?

前端 未结 6 756
情书的邮戳
情书的邮戳 2020-12-02 14:24

Being new to ASP.NET MVC, I\'ve been wondering about the signature of Controller methods. In all the examples I\'ve seen, they always seem to return ActionResult, even if th

6条回答
  •  囚心锁ツ
    2020-12-02 14:55

    Yes, you can define your action like: public ViewResult Index(). But sometimes your action can return different results (it is impossible without declaring result as base ActionResult class). For example:

    public ActionResult Show()
    {
        ...
    
        if(Request.IsAjaxRequest())
        {
            return PartialView(...);
        }
    
        return View(...);
    }
    

    or:

    public ActionResult Show()
    {
        ...
    
        try
        {
            ...
        }
        catch(Exception)
        {
            return RedirectToAction(...);
        }
    
        return View(...);
    }
    

提交回复
热议问题