Generate a text file and download it in your local machine in ASP.NET MVC

In the below example i have generate a text file and download it in your local machine

Create a model class for example
public class Information
{
public string FirstName { get; set; }
}

then create a controller and two action results
using System.IO;
using System.Text;
using MvcApplication1.Models;
using System.Web.Mvc;
namespace MvcApplication1.Controllers
{
public class SampleController : Controller
{
[HttpPost]
public ActionResult Create(Information information)
{
var byteArray = Encoding.ASCII.GetBytes(information.FirstName);
var stream = new MemoryStream(byteArray);
return File(stream, "text/plain", "your_file_name.txt");
}
[HttpGet]
public ActionResult Create()
{
return View();
}
}
}

Create a view by right clicking anyone of the Create action result. Your view code will be like below

@model MvcApplication1.Models.Information

@{
    ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm()) {
    <fieldset>
        <legend>Information</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.FirstName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.FirstName)
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

Run the application and give some value as FirstName and click Create button, a file will be downloaded in your local machine by writing the input text.

Enjoy coding..

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s