简体   繁体   中英

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

I need to pass my upload file to my controller using 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) {

            }
        })
})

View:

@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

Controller:

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

public void Register(RegisterViewModel model)
{

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

    }

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

I can get the model value just fine but Request.Files always returns null. I also tried using HttpPostedFileBase but it also always return null

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

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

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

First you need to give you file control a name attribute so it can post back a value to your controller

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

Then serialize your form and the associated file(s)

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

and post back with

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

Note also the file input needs to be inside the form tags

You need to use FormData with combination of contentType, processData setting to 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM