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

 

  1. public class WordActionResult : ActionResult  
  2. {  
  3.     string path;  
  4.     public WordActionResult(string filePath)  
  5.     {  
  6.         if (string.IsNullOrEmpty(filePath))  
  7.         {  
  8.             throw new ArgumentNullException("File path is null or empty");  
  9.         }  
  10.         path = filePath;  
  11.     }  
  12.     public override void ExecuteResult(ControllerContext context)  
  13.     {  
  14.         Var bytes = File.ReadAllBytes(context.HttpContext.Server.MapPath(path));  
  15.         context.HttpContext.Response.ContentType = "application/msword";  
  16.         context.HttpContext.Response.BinaryWrite(bytes);  
  17.     }  
  18. }

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.

  1. @{  
  2.     ViewBag.Title = "Index";  
  3. }   
  4. <h2>Index</h2>   
  5. 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.


Similar Articles