Search code examples
jqueryasp.net-mvchttppostedfilebasejquery-ajaxq

How to Post data and one file to action with a ajax requset


i want send a multi parameter with a ajax request . for example : id=1,name="amin",logo:file . id type is int and Name type is String and Logo Type is HttpPostfileBase in my action .

var ID = $("#OfficeId").val();
if (ID == "") {
  var imagefile1 = $("#fileInput")[0].files[0];
  alert(imagefile1.name);
  $.ajax({
    url: '@Url.Action("Create", "Administration")',
    data: { ID: ID, Name: $("#Name").val(), ManagerName: $("#ManageName").val(), UserName: $("#UserName").val(), Password: $("#Password").val(), Address: $("#Address").val(), Wage: $("#Wage").val(), Logo: imagefile1 },
    type: "POST",
    processData: false,
    contentType: false,
    enctype: 'multipart/form-data',
    success: function (result) {           
      if (result.Success) {
        alert(result);
      }
      eval(result.Script);
    },
    error: function () {
      alert("خطا!");
    }
  });
}

But this Code Not Work For Me. if i remove Logo(a file parameter) from ajax request, Request is work Fine. My Problem is Just Logo(a file Parameter).


Solution

  • You can use the concept of FormData object of javascript like below:

    You can give to the formData all form for processing

    var formData = new FormData();
    formData.append('ID', $("#OfficeId").val());
    formData.append('Name', $("#Name").val());
    formData.append('image', $("#fileInput")[0].files[0]); 
    

    Ajax request with jQuery will looks like this:

    $.ajax({
        url: 'Your url here',
        type: "POST",
        data: formData,
        processData: false,
        contentType: false,
        enctype: 'multipart/form-data',
        success: function (result) {
    
                    if (result.Success) {
                       alert(result);
                    }
                    eval(result.Script);
                },
                error: function () {
                    alert("خطا!");
                }
    
    })