0

I am sending a model along with the image to my controller using jquery ajax. here is my form.

  @using (Html.BeginForm(null, null, FormMethod.Post, new { id = "CreateUser" ,enctype = "multipart/form-data" } ))
        {

            @Html.AntiForgeryToken();
              @Html.ValidationSummary(true)
               <fieldset>
               <div class="row">
                    <div class="col-xs-6">
                        @*----FIRST NAME----*@
                        <label>
                            First Name <span class="text-red font12">*</span>
                        </label>
                        @Html.TextBoxFor(model => model.FirstName, new { @class = "form-control", id = "txtFirstName", @maxlength = "30" })
                    </div>


                    <div class="col-xs-6">
                        @*----LAST NAME----*@
                        <label>
                            Last Name <span class="text-red font12">*</span>
                        </label>

                        @Html.TextBoxFor(model => model.LastName, new { @class = "form-control", id = "txtLastName", @maxlength = "30" })
                    </div>

               <div class="col-xs-6">
                        @*----Logo Upload----*@

                        <label>
                           Logo Uploaad <span class="text-red font12">*</span>
                        </label>
                        <div class="input-group">


                            <input type="file" id="FileUpload1" />

                        </div>

                    </div>
                </div>

        <div class="row">
                    <div class="col-xs-4" style="float:right;">
                        <input type="button" value="Save" class="btn btn-primary btn-block btn-flat" onclick="validateandcreate();" />
                    </div>
                </div>

} here is my jquery code

function CreateUser() {

    var username = $("#txtUserName").val();

    var fileUpload = $("#FileUpload1").get(0);
    var files = fileUpload.files;

    var fileData = new FormData();  

    // Looping over all files and add it to FormData object  
    for (var i = 0; i < files.length; i++) {  
        fileData.append(files[i].name, files[i]);  
    }  


    debugger;
    if (username != "") {

        var model = {
            "FirstName": encodeURIComponent($("#txtFirstName").val()),
            "LastName": encodeURIComponent($("#txtLastName").val())
        };


        $.ajax({
            url: '/User/Create',
            method: 'post',
            dataType: 'json',
            data: { m: model, f: fileData },
            success: function (data) {
              alert("success");
            },
            error: function (err) {

               alert("error");
            }
        });
    }
}

it is working perfectly if i am sending only the model,but does not hit the controller if I send the uploaded image along with it. here is my contrller.

   [HttpPost]
    //[AuthorizationFilter]
   [ValidateAntiForgeryToken]
    public JsonResult Create(Models.Users user, HttpPostedFileBase file_Uploader)
    {
   //code
    }
akash
  • 173
  • 1
  • 14

1 Answers1

2

You need to set processData: false and contentType: false on your ajax to submit files through jQuery.ajax()

You can also add data other than files into your FormData.

var formdata = new FormData();
formdata.append("file", fileobject);
formdata.append("model", JSON.stringify({
  name: "Johny",
  lastname: "Good"
}));

$.ajax({
  url: '/User/Create',
  method: 'post',
  dataType: 'json',
  contentType: false,
  processData: false,
  data: formdata,
  success: function(data) {
    alert("success");
  },
  error: function(err) {

    alert("error");
  }
});

See Ajax File Uploads

Graham
  • 7,431
  • 18
  • 59
  • 84
Ozan
  • 3,709
  • 2
  • 18
  • 23
  • but I want to pass both i.e model(firstname,lastname) and filedata(uploaded image) in a single ajax post – akash Aug 10 '16 at 06:27
  • the above solution is working only if i am sending the uploaded image to the controller – akash Aug 10 '16 at 06:28
  • You can add as much data as you want into your formdata. append your modal object to formdata as a stringified json and parse it server-side, or append its key-value pairs into formdata as seperate key-value pairs. Whichever you perefer works. I updated the answer showing how to send other data along with files. – Ozan Aug 10 '16 at 06:30
  • I am getting only this error on the clientside now.i.e fdata is not defined while posting through ajax – akash Aug 10 '16 at 06:48
  • I have used and var fdata = new FormData(); though – akash Aug 10 '16 at 06:48
  • That error would be thrown because `fdata` is not defined when you try to reach it. Make sure you define it before you try to reach it and it is reachable. Without the rest of your code and exact line the error is thrown I can't tell more. – Ozan Aug 10 '16 at 06:52
  • I was using ValidateAntiForgeryToken which was causing the problem.I removed that token and it worked absolutly fine. thanks man. – akash Aug 11 '16 at 06:07
  • If you want to use AntiForgeryToken with ajax forms, you can make it work with a little bit of manual work. Get the tokens value from the form you put it in and append it to the formdata with the key `__RequestVerificationToken`. See http://stackoverflow.com/questions/4074199/jquery-ajax-calls-and-the-html-antiforgerytoken for more details. – Ozan Aug 11 '16 at 06:14