In this tutorial, I am going to explain you how to Upload file in ASP.NET MVC using jQuery Ajax method. I will be using Visual Studio 2013. Below is step by step tutorial.
Creating ASP.NET MVC Empty Application
Now the next step is to create ASP.NET MVC empty application as shown below. Go to File → New → Project. A new window will be open as shown below. Now go to Web and select .NET Framework 4.5 and give project name and click on OK .
Now new window will open as shown below. Now Select Empty Template, check on MVC checkbox and click on OK.
Now, a new project will be created as shown below.
Adding Upload Folder
Now add a new folder named UploadFiles to the root directory of the application in which the file will be uploaded or you can use specific location at hard-drive to upload files.
Adding Controller
Next step is to add controller to application. Go to controller folder and add new empty controller named as Home controller. Replace all code with below code. Here first method is Index which returns view that contains markup for file upload. Second index method is post method which is used to save the posted file from view to the hard drive.
Post index method returns result in JSON format with two custom variables success and responseMessage. success variable contains true or false and responseMessage contains different response messgaes.
using System;
usingSystem.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespaceWebApplication1.Controllers
{
publicclassHomeController : Controller
{
publicActionResult Index()
{
return View();
}
[HttpPost]
[ActionName("Index")]
publicJsonResult Index_Post()
{
bool flag = true;
string responseMessage = string.Empty;
if (Request.Files.Count > 0)
{
HttpPostedFileBase file = Request.Files[0];
//add more conditions like file type, file size etc as per your need.
Now, right click on home controller index action method, add new view and name Index. Select Empty template and uncheck Use layout page and click on Add as shown below.
Now go to Views / Home folder, open Index.cshtml file and replace all code with below code. Here first file is jquery.min.js which is compulsory file and other two bootstrap files are used for styling the View.