簡體   English   中英

MVC5 - 如何使用 jquery ajax 將文件上傳和模型一起傳遞給控制器

[英]MVC5 - How to pass fileupload along with model to controller using jquery ajax

我需要使用 jquery ajax 將我的上傳文件傳遞給我的控制器。

JS:

$('#btnpopupreg').click(function () {
        $.ajax({
            type: 'POST',
            url: '/Membership/Register',
            data: $('#frmRegister').serializeArray(),
            dataType: 'json',
            headers: fnGetToken(),
            beforeSend: function (xhr) {

            },
            success: function (data) {
                //do something
            },
            error: function (xhr) {

            }
        })
})

看法:

@model Test.RegisterViewModel

@{
       using Html.BeginForm(Nothing, Nothing, FormMethod.Post, New With {.id = "frmPopUpRegister", .enctype = "multipart/form-data"})
}

<input type="file" />
//rest of my strongly typed model here
<input type="button" value="BUTTON" />
//rest of the code here

控制器:

[HttpPost()]
[AllowAnonymous()]
[ValidateAntiForgeryToken()]

public void Register(RegisterViewModel model)
{

    if (Request.Files.Count > 0) { //always 0

    }

    if (ModelState.IsValid) {
          //do something with model
    }
}

我可以很好地獲得模型值,但 Request.Files 總是返回 null。 我也嘗試使用 HttpPostedFileBase 但它也總是返回 null

[HttpPost()]
[AllowAnonymous()]
[ValidateAntiForgeryToken()]

public void Register(RegisterViewModel model, HttpPostedFileBase files)
{
    //files always null

    if (ModelState.IsValid) {
          //do something with model
    }
}

首先,您需要為文件控件提供一個name屬性,以便它可以向您的控制器回發一個值

<input type="file" name="files" /> // 

然后序列化您的表單和相關文件

var formdata = new FormData($('form').get(0));

並回貼

$.ajax({
  url: '@Url.Action("Register", "Membership")',
  type: 'POST',
  data: formdata,
  processData: false,
  contentType: false, 
  success: function (data) {
    ....
  }        
});

還要注意文件輸入需要在表單標簽內

您需要將FormData與 contentType、processData 設置為 false 結合使用:

    var formData = new FormData();
        formData.append("userfile", $('#frmRegister input[type="file"]')[0].files[0]);
        // append the file in the form data
    $.ajax({
      type: 'POST',
      url: '/Membership/Register',
      data: formdata, // send it here
      dataType: 'json',
      contentType:false, // this
      processData:false, // and this should be false in case of uploading files
      headers: fnGetToken(),
      beforeSend: function(xhr) {

      },
      success: function(data) {
        //do something
      },
      error: function(xhr) {

      }
    })
<input type="file" id="LogoImage" name="image" />
<script>

var formData = new FormData($('#frmAddHotelMaster').get(0));

var file = document.getElementById("LogoImage").files[0];

formData.append("file", file);


        $.ajax({
            type: "POST",
            url: '/HotelMaster/SaveHotel',
            data: formData,
            dataType: 'json',
            contentType: false,
            processData: false,
            success: function (response) {
                swal({
                        title: "Good job!",
                        text: "Data Save successfully!",
                        type: "success"
                    });
                    $('#wrapper').empty();
                    $('#wrapper').append(htmlData);
            },
            error: function (error) {
                alert("errror");
            }
        });
</script>

public ActionResult SaveHotel(HotelMasterModel viewModel, HttpPostedFileBase file)
{

            for (int i = 0; i < Request.Files.Count; i++)
            {
                var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath("~/App_Data/"), fileName);
                file.SaveAs(path);
            }
return View();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM