MVC : Create text file and download - Free Asp.Net,MVC,AngularJs,Jquery,Javascript,Sql Server,WCF,Entity framework snippets and tutorial


MVC : Create text file and download

In this article I am going to explain how to create text file and download using asp.net MVC.

Description:
I want to write text enter in textbox to Text file and download that text file.

Implementations:

Add controller
First of all add an empty controller to project. Create Action to create text file and download.

Complete Code of Controller:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Text;
namespace mvctest2017.Controllers
{
    public class TextFileController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult CreateTextFile()
        {
            return View();
        }

        [HttpPost]
        public ActionResult CreateTextFile(string message)
        {
            string path = Server.MapPath("~/aspmantra.txt");
            using (StreamWriter sw = System.IO.File.CreateText(path))
            {
                sw.WriteLine(message);
            }
            return File(path,"text/plain","aspmantra.txt");
        }
     
    }
}


Add view

Now add view to Createtextfile action.

Complete Source of View:

@{
    ViewBag.Title = "Create Text File";
}

@using(Html.BeginForm())
{
    <table>
        <tr>
            <td><label>Enter Text :</label></td>
            <td>@Html.TextArea("message", new { cols = 50, rows = 8 })</td>
        </tr>
        <tr>
            <td></td>
            <td><input id="Submit1" type="submit" value="Ctreate Text File" /></td>
        </tr>
    </table>   
}

  

What do you think about this article?

If you found this article useful, please share and follow on Facebook, Twitter, Google Plus and other social media websites. To get free updates subscribe to newsletter. Please put your thoughts and feedback in comments section.

Share this

Share on FacebookTweet on TwitterPlus on Google+
loading...


EmoticonEmoticon