File Upload uisng Jquery in C# ASP.Net MVC

There so many ways to upload files with jqueries in ASP.Net C#. One way is with creating XMLHttpRequest and another way is with FormData object.
In this post i’ll show uploading files and saving form data in one ajax call using jquery.

Upload Files with Jquery in ASP.Net MVC C#

First code for View which represents normal html code of form


@model modelname







File Upload








@Html.TextBoxFor(m => m.File, new { @type = "file", @multiple = "multiple" })





@Html.TextBoxFor(m => m.Field1, new { @class = "form-control datepicker" })
@Html.ValidationMessageFor(m => m.Field1)








MVC Controller Code for Saving File
In controller create action method with two arguments one is for formdata and another one is for List of HttpPostedFileBase Class which represents multiple files that you select.

public JsonResult SaveFilesWithFormData(ModelName FormData, List Of HTTPPostedFileBase Files) //Model Name represents class provided in view
{
try
{
//logic for saving data into database

//save multiple files
foreach (var upload in File)
{
if (upload != null)
{
string pathToSave = "folderpath";

//Check folder is exist or not if not then it will creates folder
if (!Directory.Exists(pathToSave))
{
Directory.CreateDirectory(pathToSave);
}

//get file name for selected file
string filename = Path.GetFileName(upload.FileName);

//save file
upload.SaveAs(pathToSave + filename);
}
}
msg = "Success";
}
catch (Exception ex)
{
Log.Error(ex.Message);
}
return Json(msg, JsonRequestBehavior.AllowGet);
}

Hope that above code will help you to save files easily with form data into server. Keep coding