Using Text Custom ActionResult in MVC 3.0

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..

Up Next
    Ebook Download
    View all
    Learn
    View all