ChatGPT解决这个技术问题 Extra ChatGPT

Difference Between ViewResult() and ActionResult()

What is the difference between ViewResult() and ActionResult() in ASP.NET MVC?

public ViewResult Index()
{
    return View();
}

public ActionResult Index()
{
    return View();
}
Great question. I watched a video and to create unit tests the instructor first changed the return type of the Action he was going to test from ActionResult to ViewResult. No explanation....I was like "What we can just randomly change types? With no explanation"
Probably this documentation is helpful :) msdn.microsoft.com/en-us/library/…

S
SeanKilleen

ActionResult is an abstract class that can have several subtypes.

ActionResult Subtypes

ViewResult - Renders a specifed view to the response stream

PartialViewResult - Renders a specifed partial view to the response stream

EmptyResult - An empty response is returned

RedirectResult - Performs an HTTP redirection to a specifed URL

RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data

JsonResult - Serializes a given ViewData object to JSON format

JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client

ContentResult - Writes content to the response stream without requiring a view

FileContentResult - Returns a file to the client

FileStreamResult - Returns a file to the client, which is provided by a Stream

FilePathResult - Returns a file to the client

Resources

What's the difference between ActionResult and ViewResult for action method? [ASP.NET Forums]


what is the advantage of returning ViewResult over ActionResult - is it just a bit more semantic and shows your intent - but in practice makes no difference usually?
R
RPM1984

ActionResult is an abstract class.

ViewResult derives from ActionResult. Other derived classes include JsonResult and PartialViewResult.

You declare it this way so you can take advantage of polymorphism and return different types in the same method.

e.g:

public ActionResult Foo()
{
   if (someCondition)
     return View(); // returns ViewResult
   else
     return Json(); // returns JsonResult
}

Does it mean that we should always return ActionResult so that we get the advantage of it. Or is there any limitation or side effect of this?
@Adarsh - it's the same with any abstract class in C#. Declare it that way if you want to encapsulate the implementation inside the method or want to future proof your API for other derived typed. If not, use the concrete. I generally use the concrete (e.g ViewResult or JsonResult)
R
RickAndMSFT

It's for the same reason you don't write every method of every class to return "object". You should be as specific as you can. This is especially valuable if you're planning to write unit tests. No more testing return types and/or casting the result.


Cleaner code and unit testing is the benefit of using ViewResult based on my experience.
R
Robert Levy

ViewResult is a subclass of ActionResult. The View method returns a ViewResult. So really these two code snippets do the exact same thing. The only difference is that with the ActionResult one, your controller isn't promising to return a view - you could change the method body to conditionally return a RedirectResult or something else without changing the method definition.


C
Community

While other answers have noted the differences correctly, note that if you are in fact returning a ViewResult only it is better to return the more specific type rather than the base ActionResult type. An obvious exception to this principle is when your method returns multiple types deriving from ActionResult.

For a full discussion of the reasons behind this principle please see the related discussion here: Must ASP.NET MVC Controller Methods Return ActionResult?


A
Andrew Stubbs

In the Controller , one could use the below syntax

public ViewResult EditEmployee() {
    return View();
}

public ActionResult EditEmployee() {
    return View();
}

In the above example , only the return type varies . one returns ViewResult whereas the other one returns ActionResult.

ActionResult is an abstract class . It can accept:

ViewResult , PartialViewResult, EmptyResult , RedirectResult , RedirectToRouteResult , JsonResult , JavaScriptResult , ContentResult, FileContentResult , FileStreamResult , FilePathResult etc.

The ViewResult is a subclass of ActionResult.


I'm not sure if this is what you meant, but just in case I want to clarify that you can't have those two methods at the same time, as their name and (no) parameters are the same. It's not possible to overload a method by only changing the result type.
added details in the interview question blog post topinterviewquestion.com/article/…
A
Abhishek Duppati

In Controller i have specified the below code with ActionResult which is a base class that can have 11 subtypes in MVC like: ViewResult, PartialViewResult, EmptyResult, RedirectResult, RedirectToRouteResult, JsonResult, JavaScriptResult, ContentResult, FileContentResult, FileStreamResult, FilePathResult.

    public ActionResult Index()
                {
                    if (HttpContext.Session["LoggedInUser"] == null)
                    {
                        return RedirectToAction("Login", "Home");
                    }

                    else
                    {
                        return View(); // returns ViewResult
                    }

                }
//More Examples

    [HttpPost]
    public ActionResult Index(string Name)
    {
     ViewBag.Message = "Hello";
     return Redirect("Account/Login"); //returns RedirectResult
    }

    [HttpPost]
    public ActionResult Index(string Name)
    {
    return RedirectToRoute("RouteName"); // returns RedirectToRouteResult
    }

Likewise we can return all these 11 subtypes by using ActionResult() without specifying every subtype method explicitly. ActionResult is the best thing if you are returning different types of views.


w
wjxie

To save you some time here is the answer from a link in a previous answer at https://forums.asp.net/t/1448398.aspx

ActionResult is an abstract class, and it's base class for ViewResult class.

In MVC framework, it uses ActionResult class to reference the object your action method returns. And invokes ExecuteResult method on it.

And ViewResult is an implementation for this abstract class. It will try to find a view page (usually aspx page) in some predefined paths(/views/controllername/, /views/shared/, etc) by the given view name.

It's usually a good practice to have your method return a more specific class. So if you are sure that your action method will return some view page, you can use ViewResult. But if your action method may have different behavior, like either render a view or perform a redirection. You can use the more general base class ActionResult as the return type.