Friday, April 29, 2016

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

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
        //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))

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

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

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