ARTICLE

Using Text Custom ActionResult in MVC 3.0

Posted by Amit Patel Articles | ASP.NET MVC with C# July 13, 2012
In this article I am trying to explain how to create a custom action in an ASP.NET MVC Application.
Reader Level:
 

You can write a custom action for Excel, Word, Image, Text etc.

Here I am going to create a custom action for a Text file.

Steps to create Custom Action Handler.

Step 1: Create a new MVC project.

First.png

Step 2: We will create a source folder from where we will read a text file. I have created the File folder:

Second.png

Step 3: Now we will create a new class and that class will inherit from ActionResult. It will look like this:

public class TextResult : ActionResult
{
    public string Path { get; set; }
    public string FileName { get; set; }
    public override void ExecuteResult(ControllerContext context)
    {
        var filepath = context.HttpContext.Server.MapPath(Path);
        var data = File.ReadAllText(filepath + "\\" + FileName);
        context.HttpContext.Response.Write(data);
    }
}


We have to override the ExecuteResult method in your custom Result class.

Step 4: Now we will add a new controller; in this sample I created a TextController class:

public class TextController : Controller
{
    public TextResult Index()
    {
        return new TextResult { FileName = "Mahesh.txt", Path = "File" };
    }
}


Note:- I have only added a controller, not a view.

Step 5:
Now we will run our application.

third.png

I am also attaching sample code for this article. Hope it will help you.

Happy Coding..

Login to add your contents and source code to this article
comments
COMMENT USING
PREMIUM SPONSORS
DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and add new content to existing PDF documents from within your applications.
Get Career Advice from Experts
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Join a Chapter