Difference between Viewresult and Actionresult

Asked

Viewed 2,858 times

6

What’s the difference between Viewresult and Actionresult? I usually call a View using an Actionresult, but I’ve seen code with Viewresult. Then this doubt arose.

2 answers

7


ViewResult drift ActionResult. ActionResult is abstract, and serves as wildcard in return, which can be:

  • I liked the Gypsy explanations. I was looking at the Viewresult documentation and realized that it is also an abstract class the doubt arose because I saw a controller method using Actionresult and another controller method called a View using Viewresult instead of Actionresult. If I understand your explanations correctly, it doesn’t matter if I call a View with Actionresult or Viewresult?

  • Exactly, ActionResult, by being more generic, supports not only return View() as well as any other return as those mentioned in the reply. ViewResult will therefore only accept return View() or some method that returns only ViewResult, what may turn out to be a limiter.

  • 1

    Thank you for the reply!

4

Of a response from forum of ASP.NET: ActionResult is an abstract class, and has derived classes, including ViewResult. If you will return in your method a Viewresult, you can declare it either by returning Actionresult or Viewresult.

These are some classes derived from Actionresult:

  • Viewresult
    • Returns a view to be rendered in the answer
  • Partialviewresult
    • Returns a partial view to be rendered in the answer
  • Emptyresult
    • "Nothing"; an empty answer (HTTP response with contents of size 0, or 204 No Content)
  • Redirectresult
    • Returns a redial (HTTP 3xx) to the specified URL
  • Redirecttorouteresult
    • Returns a redial (HTTP 3xx) for the specified route
  • Jsonresult
    • Returns a data in JSON format (application/json)
  • Who voted negative? The answer is correct.

  • Carlos, the code that gave rise to my doubt is this one below. Within the method itself were used two types of calling a View. The First using Actionresult and the second calling its derived class which is also abstract, the Viewresult: public Actionresult Change(Product product) { Return View(product); } public Viewresult New() { Return View("Change", new Product(); }

  • 1

    Pro ASP.NET, a action need to return a ActionResult, or one of its derived classes - in your case, it will make no difference. An advantage of declaring the method by returning the concrete type (for example, ViewResult), is that it prevents that in the future someone will change the type of return by mistake (and that’s what the compiler will focus on, not ASP.NET).

  • Thanks Carlos for the help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.