Saturday, December 12, 2015

Differences Between ViewResult() and ActionResult()

Let's look at the difference between ViewResult() and ActionResult() in ASP.NET MVC.

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

public ActionResult Index()
{
    return View();
}
ActionResult() is a general result type that can have several subtypes (Ref:ASP.NET MVC 1.0 Quickly" Book)

a) ViewResult : Renders a specified view to the response stream
b) PartialViewResult : Renders a specified partial view to the response stream
c) EmptyResult : Basically does nothing; an empty response is given
d) RedirectResult : Performs an HTTP redirection to a specified URL
e) RedirectToRouteResult : Performs an HTTP redirection to a URL that is determined  by the routing engine, based on given route data
f) JsonResult : Serializes a given ViewData object to JSON format
g) JavaScriptResult : Returns a piece of JavaScript code that can be executed on
the client
h) ContentResult : Writes content to the response stream without requiring  a view
i) FileContentResult : Returns a file to the client
j) FileStreamResult : Returns a file to the client, which is provided by a Stream
k) FilePathResult : Returns a file to the client

In MVC framework, it uses ActionResult class to reference the object your action method returns. And invokes ExecuteResult method on it. 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 behaviour, like either rendering a view or performing a redirection. You can use the more general base class ActionResult as the return type.

(Ref::http://forums.asp.net/)

No comments:

Post a Comment