MVC : Create text file and download | ASPMANTRA | Asp.Net,MVC,AngularJs,Jquery,Javascript,Sql Server AND WCF 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>   
}

  

Post a Comment

[blogger]

MKRdezign

Contact Form

Name

Email *

Message *

Powered by Blogger.
Javascript DisablePlease Enable Javascript To See All Widget