Pass (Send) multiple file along with form data to Controller using jQuery Ajax in ASP.Net MVC

Category > ASP.NET || Published on : Sunday, February 20, 2022 || Views: 76 || Pass (Send) multiple file form data to Controller using jQuery Ajax in ASP.Net MVC


Here Pawan Kumar will explain how to Pass (Send) multiple file along with form data to Controller using jQuery Ajax in ASP.Net MVC

Controller

ublic class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public JsonResult Upload()
    {
        if (Request.Files.Count > 0)
        {
            string name = Request.Form["name"];
            for (int i = 0; i < Request.Files.Count; i++)
            {
                HttpPostedFileBase postedFile = Request.Files[i];
                string fileName = Path.GetFileName(postedFile.FileName);
 
                string path = Server.MapPath("~/Uploads/");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                postedFile.SaveAs(path + fileName);
            }
        }
        return Json("Data saved successfully.");
    }
}

View

@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#btnUpload").click(function () {
                var formData = new FormData();
                formData.append('name', $("#txtName").val());
                var files = $("#fuUpload").get(0).files;
                for (var i = 0; i < files.length; i++) {
                    formData.append(files[i].name, files[i]);
                }
                $.ajax({
                    url: "/Home/Upload",
                    type: 'POST',
                    cache: false,
                    contentType: false,
                    processData: false,
                    data: formData,
                    success: function (response) {
                        alert(response);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <form id="Dtls">
        <table>
            <tr>
                <td>Title</td>
                <td><input type="text" id="txtName" name="txtName" /></td>
            </tr>
            <tr>
                <td>Select File</td>
                <td><input id="fuUpload" type="file" name="postedFile" multiple="multiple" /></td>
            </tr>
        </table>
        <hr />
        <input type="button" id="btnUpload" value="Upload" />
    </form>
</body>
</html>