1

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
    }
}
1

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

4 Comments

not working, it doesn't even hit my controller. If I remove processData and contentType, it works, but files still null.
It does work (check the url is correct). There must be other issues with your code - your view indicates there aren't even any controls within the form.
Is it possible to do the same thing but to have the HttpPostedFileBase in the RegisterViewModel model?
@smoksnes, Absolutely, and that is the preferred way to do it.
0

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

      }
    })

1 Comment

isn't this code will only send uploaded file to my controller? How about the model?
0
<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();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.