How to Create Custom ActionResult Method in ASP.Net MVC4

My last article explained asynchronous action methods in ASP.Net MVC4 web applications. This article will explain how to create custom action methods in ASP.Net MVC4.

Custom ActionResult Method

ASP.Net MVC provides a way to create our own ActionResult for Controllers. Basically when we call an action method, it will return a view from the controller based on the name of your action. But when you want to do something in an Action that you don't want to render on the view, you can extend Ac­tion­Re­sult, to do it.

Let's create an example to explain the custom action in ASP.Net MVC4.

Setup the Project

Use the following procedure in this article to create a project named "CustomActionResultInMVC4". Once you are done, create a folder under the project's base folder as shown below.

Custom-Action-Result-in-MVC4.jpg

Create a class named "WordActionResult" in the CustomActions folder.

WordActionResult Class

public class WordActionResult : ActionResult

{

    string path;

    public WordActionResult(string filePath)

    {

        if (string.IsNullOrEmpty(filePath))

        {

            throw new ArgumentNullException("File path is null or empty");

        }

        path = filePath;

    }

    public override void ExecuteResult(ControllerContext context)

    {

        Var bytes = File.ReadAllBytes(context.HttpContext.Server.MapPath(path));

        context.HttpContext.Response.ContentType = "application/msword";

        context.HttpContext.Response.BinaryWrite(bytes);

    }

}

Here in the code above, we are setting the path from the constructor parameter. When the ExecuteResult is executed, we are reading all the bytes from Word document and writing it to the current response.

The Index View

In the Index view, we have an action link to download the Word Document.

@{
    ViewBag.Title = "Index";
} 
<h2>Index</h2> 
Click @Html.ActionLink("here", "Word", new { filePath = "~/App_Data/file.docx" }) to Download this article in Word Format

In this action link, we are passing the document file path to be downloaded. If you click on the word "here" then you can download this article into a Word document.

Note

If you don't append the "~/" then Server.MapPath() will map the path, like "/Home/App_Date/file.docx".

This is how to create our custom action result for the controller.

Up Next
    Ebook Download
    View all
    Learn
    View all