Asp.Net Mvc jQuery ajax multiple file upload post

Selamlar,

Asp.Net Mvc projemizde, jQuery ile form içerisindeki elemanları ajax ile nasıl post edeceğimiz paylaşmak istiyorum.

Yapılacak işlemler;

  1. GalleryItemAddEdit.cshtml sayfamızı aşağıdaki gibi hazırlıyoruz; (<input type="file" name="fuDosya" multiple="" /> çoklu resim için bu kısım eklenmeli.)
    @{
        ViewBag.Title = ViewBag.HeaderText;
        Layout = "/Views/Shared/_LayoutAccountMaster.cshtml";
    }
    @model Core.tGalleryItem
     
    <div class="container-fluid">
        <div class="row">
            <div class="col-lg-12 col-md-12">
                <div class="card">
                    <div class="content">
                        <form id="frmGalleryAddEdit">
                            @Html.AntiForgeryToken()
                            <input type="hidden" name="txtHiddentGalleryItemID" id="txtHiddentGalleryItemID" value="@Model.tGalleryItemID" />
                            <input type="hidden" name="txtHiddentGalleryID" id="txtHiddentGalleryID" value="@Request.QueryString["tGalleryID"]" />
                            <input type="hidden" name="txtHiddenPath" id="txtHiddenPath" value="@Model.Path" /> 
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label>Başlık</label>
                                        <input class="form-control border-input" name="txtTitle" id="txtTitle" value="@Model.Title" />
                                    </div>
                                </div>
                            </div> 
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label>Dosya</label>
                                        <input type="file" id="fuDosya" name="fuDosya" multiple="" class="form-control border-input" />
                                        @Model.Path
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="form-group" id="divOncul">
                                        <label>Durum</label>
                                        @Html.DropDownListFor(model => model.IsStatus, new SelectList(Model.StatusList, "Value", "Text"), "Seçiniz...", new { @Class = "form-control border-input" })
                                    </div>
                                </div>
                            </div>
                            <div>
                                @if (Request.QueryString["id"] != null)
                                {
                                    <button type="button" class="btn btn-info btn-fill btn-wd" onclick="GalleryItemAddEditFormPost();"><i class="glyphicon glyphicon-floppy-disk"></i> Güncelle</button>
                                }
                                else
                                {
                                    <button type="button" class="btn btn-info btn-fill btn-wd" onclick="GalleryItemAddEditFormPost();"><i class="glyphicon glyphicon-floppy-disk"></i> Ekle</button>
                                }
                            </div>
                            <div class="clearfix"></div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="/Content/Script/GalleryItemAddEdit.js"></script>


    2. GalleryItemAddEdit.js Dosyamızın içeriğini aşağıdaki gibi hazırlıyoruz;

    $(document).ready(function () {
    });
    
    function GalleryItemAddEditFormPost() {
        var formData = new FormData();
        formData.append("__RequestVerificationToken", $("input[name=__RequestVerificationToken]").val());
        formData.append("txtTitle", $("#txtTitle").val());
        formData.append("txtHiddentGalleryID", $("#txtHiddentGalleryID").val()); 
        formData.append("txtHiddentGalleryItemID", $("#txtHiddentGalleryItemID").val()); 
        formData.append("txtHiddenPath", $("#txtHiddenPath").val()); 
        formData.append("IsStatus", $("#IsStatus").val());
    
        jQuery.each(jQuery('#fuDosya')[0].files, function (i, file) {
            formData.append('file-' + i, file);
        });
    
        $.ajax({
            type: "POST",
            url: "/Admin/GalleryItemAddEditAjax",
            data: formData,
            dataType: 'json', 
            contentType: false, // burası önemli.
            processData: false, // burası önemli.
            success: function (data) {
                if (data.ReturnCode === 0) {
                    $.notify({ icon: 'ti-info-alt', message: data.ReturnMessages + "<br> <a href='/Admin/GalleryItemList?tGalleryID=0'>İçerik Listesi</a>" }, { type: 'success', timer: 90000, placement: { from: 'top', align: 'center' } });
                } else {
                    $.notify({ icon: 'ti-info-alt', message: data.ReturnMessages }, { type: 'warning', timer: 3000, placement: { from: 'top', align: 'center' } });
                }
            },
            error: function (data) {
                console.log(data);
            }
        });
    } 


    3. GalleryItemAddEditAjax Controller'ımızı da aşağıdaki gibi hazırlıyoruz.

            [HttpPost]
            [ValidateInput(false)] 
            [ValidateAntiForgeryToken]
            public JsonResult GalleryItemAddEditAjax()
            {
                NameValueCollection nvc = HttpContext.Request.Form;
    
                tGalleryItem otGalleryItem = new tGalleryItem();
                otGalleryItem.tGalleryID = string.IsNullOrEmpty(nvc["txtHiddentGalleryID"]) ? 0 : int.Parse(nvc["txtHiddentGalleryID"]);
                otGalleryItem.tGalleryItemID = string.IsNullOrEmpty(nvc["txtHiddentGalleryItemID"]) ? 0 : int.Parse(nvc["txtHiddentGalleryItemID"]);
                otGalleryItem.Title = nvc["txtTitle"];
                otGalleryItem.Path = string.IsNullOrEmpty(nvc["txtHiddenPath"]) ? null : nvc["txtHiddenPath"];
                otGalleryItem.tLanguageID = short.Parse(Session["Language"].ToString()); 
    
                if (!string.IsNullOrEmpty(nvc["IsStatus"]))
                {
                    otGalleryItem.IsStatus = bool.Parse(nvc["IsStatus"]);
                }
    
                tOperationResult result = GalleryItemValidControl(otGalleryItem);
    
                if (result.ReturnCode == 0)
                {
                    if (Request.Files.Count > 0)
                    {
                        for (int i = 0; i < Request.Files.Count; i++)
                        {
                            HttpPostedFileBase file = Request.Files[i];
    
                            //int fileSize = file.ContentLength;
    
                            string mimeType = file.ContentType;
                            string fileExtension = Path.GetExtension(file.FileName);
                            string fileName = DateTime.Now.Day.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString() + DateTime.Now.Hour.ToString() +
                                DateTime.Now.Second.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Millisecond.ToString() + fileExtension;
    
                            if (mimeType.ToLower() == "video/mp4" && fileExtension.ToLower() == ".mp4" || fileExtension.ToLower() == ".pdf")
                            {
                                file.SaveAs(Server.MapPath("/Assets/file/" + fileName));
                                otGalleryItem.Path = fileName;
                            }
                            else
                            {
                                ImageHelper.CreateUpload(file.InputStream, fileName, 350, "/Assets/galeri/kucuk/");
                                ImageHelper.CreateUpload(file.InputStream, fileName, 1000, "/Assets/galeri/buyuk/");
                                otGalleryItem.Path = fileName;
                            }
    
                            if (otGalleryItem.tGalleryItemID == 0)
                            {
                                Core.GalleryItem.InsertGalleryItem(otGalleryItem);
                                result.ReturnMessages = "Kayıt eklendi.";
                            }
                            else
                            {
                                Core.GalleryItem.UpdateGalleryItem(otGalleryItem);
                                result.ReturnMessages = "Kayıt güncellendi.";
                            }
                        } 
                    }
                     
                    return Json(result, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(result, JsonRequestBehavior.AllowGet);
                }
            }

Ve işlem tamamdır.

Projemize jQuery kütüphanesini eklemeyi unutmuyoruz*
<scriptsrc="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>