Thursday, January 15, 2015

ASP.NET MVC5 Action Methods and Action Results

In this post, I am going to talk about what Action Methods are and different Action Result Types available to us in ASP.NET MVC5.

Action Methods

An action method gets executed in response to a user request. It takes care of processing the user input and building the response to be sent to the user. If we look at the HomeController that comes with a default MVC project, we see some action methods already created.

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
...
    }


When we request /Home/Index, this action method is called which returns the view(Home/Index.cshtml).

Writing our own action methods is crucial to our MVC application development as we will be adding/editing our own functionality by adding/ editing these action methods. The return type of this action method is ActionResult.
In general, an Action Method does the stuff we write inside the method and then returns an instance of a type derived from ActionResult abstract base class.
Let's try to understand what ActionResult is and what are the other return types possible and their usages.

ActionResult

This is a generic return type for the controller action methods. It's basically an abstract class with one method: ExecuteResult()


 // Summary:

    //     Represents the result of an action method.

    public abstract class ActionResult

    {
        // Summary:

        //Enables processing of the result of an action 
        //method by a custom type that

        //inherits from the System.Web.Mvc.ActionResult
        //class.

        //

        //Parameters:

        //context:

        //The context in which the result is executed. 
        //The context information includes

        //the controller, HTTP content, request context,
        //and route data.

        public abstract void ExecuteResult(ControllerContext 
                                           context);

    }


Action methods take care of the application logic whereas ActionResults are supposed to handle framework level work such as writing to HttpResponse directly. The ExecuteResult method is called by the MVC framework to run the action result.We can override the ExecuteResult() method and write our own custom Action Result Types. Here, let's take a look at the pre-built Types which take care of most of our application needs.

Action Result Types


ContentResult
This Writes the specified content directly to the response as text. We can use this for any content type. We can specify the content encoding and content type. Using this, we can give the system whatever response we want.

EmptyResult
Returns a null or empty response. We can use it for blank page.

FileContentResult
This is derived from the abstract class FileResult. This is used to read the file contents and then write byte array to response's output stream.

FilePathResult
This is also derived from FileResult abstract class. This is useful when we want to read the file from a specific path. Using this we can write the file directly to the response from the specified path.

FileResult
This is just an abstract base class which is used by other types for returning files to the user. It contains an abstract method WriteFile() which is overridden by the other types deriving from it. FileContentResult, FilePathResult and FileStreamResult derive from this.

FileStreamResult
This is also derived from FileResult abstract class. This is useful when we want to read the file and write a stream to the response.

HttpNotFound
This is used to send the HTTP 404 Not Found response to the client. This is derived from HttpStatusCodeResult.

HttpStatusCodeResult
This is used to return a specific HTTP Code and description to the client. 

HttpUnauthorizedResult
This is used to send the HTTP 401 Not Authorized response to the client. This is also derived from HttpStatusCodeResult.

JavaScriptResult
This is used to send Javascript code to the client to be execute immediately. Here, the content type is automatically set to “application/x-javascript”.

JsonResult
This uses javascript serializer to return the data serialized in JSON format. Here, the content type is automatically set to “application/json”. This is typically used to return response for AJAX requests.

PartialViewResult
This is used to render partial view to the response. This is also typically used to return response for AJAX requests. Internally, it calls its FindPartialView method to find the partial view to be rendered.

RedirectResult
This is used to perform HTTP redirect to a specified URL. It sends response with status code 302 Object Moved. This will cause the client to issue a new request immediately to the specified URL.

RedirectToRouteResult
This is also used to perform HTTP redirect similarly but instead of a specific URL, we just mention the route and then routing API is used to get the URL.

ViewResult
This is the last but most widely used Result Type. This is derived from ViewResultBase class. The FindView method is used to locate the view and the Render method is used to render the output to the response.


These different result types give us a lot of power to deal with different scenarios effectively. They are pretty simple to learn and easy to use.


Reference: "Professional ASP.NET MVC 5"


2 comments: