Home > Software engineering >  how to post multiple models with file using ajax mvc
how to post multiple models with file using ajax mvc

Time:06-18

how can I post two model objects with a file using ajax jquery?

here is my VM class

 public class DocumentVM
    {
        public HealthCard healthCard { get; set; }
        public EmployeeEmploymentHistory empHistory { get; set; }
        public IFormFile attachmentFile { get; set; }
    }

here is my ajax with two methods where I am creating objects. objects are ok! but when I post with a file using formData object cannot bind and when I use the simple js object the models are binding but the file's not how can I solve this? can anyone help with this?

function SaveDocumentData() {
    debugger
    $('#spinneraj').show();
  //  var healthCard = getDocumentObject();
    //  var empHistory = getEmploymentHistory();
    var formData = new FormData();
    var attachment = $('#AttachmentFile').val();
    if (attachment)
    {
        formData.append("attachmentFile",$('#AttachmentFile')[0].files[0]);
    }
    formData.append("healthCard", JSON.stringify(getDocumentObject()));
    formData.append("empHistory", JSON.stringify(getEmploymentHistory()));
    var documentVM = {
        "healthCard": getDocumentObject(),
        "empHistory": getEmploymentHistory(),
        "attachmentFile": $('#AttachmentFile')[0].files[0]
    }

    $.ajax({

        url: jspath   '/Document/PostDocument',
        data: documentVM ,
        dataType: 'json',
        type: 'POST',
        cache: false,
        enctype: 'multipart/form-data',
        async: false,
        processData: false,
        contentType: false,
        traditional: true,
        success: function (data) {
            Swal.fire({
                position: 'top-end',
                icon: 'success',
                title: 'Document added Successfully',
                showConfirmButton: false,
                timer: 1500
            }).then(function () {
                $('#spinneraj').hide();
            })
            $('#modalAction').modal('hide');
            GetCompanyDocument();
        },
        error: function (data) {

            Swal.fire({
                position: 'top-end',
                icon: 'error',
                title: 'Oops...',
                text: data,
            }).then(function () {
                $('#spinneraj').hide();
            })
        }
    }).done(function () {
        // after ajax
        $('#spinneraj').hide();
    });
}

function getDocumentObject() {
    
    //var form = $('form#DocumentForm')[0];
    //var formData = new FormData(form);
    var object = new Object();
    var attachment = $('#AttachmentFile').val();
    if (!attachment) {
        attachment = $('#fileHealthCardCopyPath').val();
    }
    else
    {
       // object.file = $('#AttachmentFile')[0].files[0];
    }
    object.IssueDate = $('#IssueDate').val();
    object.Title = $('#DocumentTitle').val();
    object.HealthCardId = $('#HealthCardId').val();
    object.ExpiryDate = $('#ExpiryDate').val();
    object.Attachment = attachment;
    object.EntityTypeId = entityType;
    object.EntityRecId = id;

    //formData.append('IssueDate', $('#IssueDate').val());
    //formData.append('Title', $('#DocumentTitle').val());
    //formData.append('HealthCardId', $('#HCID').val());
    //formData.append('ExpiryDate', $('#ExpiryDate').val());
    //formData.append('Attachment', attachment)
    //formData.append('EntityTypeId', entityType);
    //formData.append('EntityRecId', id);

    return object;
}

function getEmploymentHistory()
{
    

    var object = new Object();
    //var form = $('form#EmpHistory-Form')[0];
    //var formData = new FormData(form);

    
    object.Title = $('#cmdTitle').val();
    object.NameSupervisor = $('#txtSupervisorName').val();
    object.CompanyName = $('#txtCompanyName').val();
    object.Designation = $('#cmbDesignation').val();
    object.SalaryCurrency = $('#cmbSaleryCurrency').val();
    object.BasicSalary = $('#txtBasicSalary').val();
    object.DurationFrom = $('#IssueDate').val();
    object.TillToDate = $('#ExpiryDate').val();
    object.Accommodation = $('#txtAccommodation').val();
    object.Transportation = $('#txtTransportation').val();
    object.Food = $('#txtFood').val();
    object.LastSalary = $('#txtLastSalary').val();
    object.OtherAllowance1 = $('#txtOtherAllowance1').val();
    object.PhoneNumber = $('#txtPhone').val();
    object.ReasonLeaving = $('#txtReasonLeaving').val();
    object.City = $('#txtCity').val();
    object.Address = $('#txtAddress').val();

  //  formData.append('Title', $('#cmdTitle').val());
   // formData.append('NameSupervisor', $('#txtSupervisorName').val());
    //formData.append('CompanyName', $('#txtCompanyName').val());
   // formData.append('Designation', $('#cmbDesignation').val());
   // formData.append('SalaryCurrency', $('#cmbSaleryCurrency').val());
   // formData.append('BasicSalary', $('#txtBasicSalary').val());
    //formData.append('DurationFrom', $('#IssueDate').val());
   // formData.append('TillToDate', $('#ExpiryDate').val());
   // formData.append('Accommodation', $('#txtAccommodation').val());
    //formData.append('Transportation', $('#txtTransportation').val());
    //formData.append('Food', $('#txtFood').val());
  //  formData.append('LastSalary', $('#txtLastSalary').val());
 //   formData.append('OtherAllowance1', $('#txtOtherAllowance1').val());
  //  formData.append('PhoneNumber', $('#txtPhone').val());
   // formData.append('PostalCode', $('#txtPostal').val());
  //  formData.append('ReasonLeaving', $('#txtReasonLeaving').val());
  //  formData.append('City', $('#txtCity').val());
  //  formData.append('Address', $('#txtAddress').val());

    return object;
}

any help will be appreciated Thanks in advance.

CodePudding user response:

For the correct usage of formData, you can refer to the following code:

Controller:

[HttpGet]
public IActionResult Test()
{
    return View();
}

[HttpPost]
public JsonResult Test(DocumentVM documentVM)
{
    var test = documentVM;
    return Json(test);
}

Model:

public class HealthCard
{
    public string IssueDate { get; set; }
    public string Title { get; set; }
    public string HealthCardId { get; set; }
}

public class EmployeeEmploymentHistory
{
    public string Title { get; set; }
    public string NameSupervisor { get; set; }
    public string CompanyName { get; set; }
}

public class DocumentVM
{
    public HealthCard healthCard { get; set; }
    public EmployeeEmploymentHistory empHistory { get; set; }
    public IFormFile attachmentFile { get; set; }
}

View:

@model _2022061301.Models.DocumentVM
<div>
    <input id="AttachmentFile" type="file" />
</div>

<div>
    <input id="IssueDate" type="text" value="IssueDate" />
    <input id="DocumentTitle" type="text" value="DocumentTitle" />
    <input id="HealthCardId" type="text" value="HealthCardId" />
</div>

<div>
    <input id="cmdTitle" type="text" value="cmdTitle" />
    <input id="txtSupervisorName" type="text" value="txtSupervisorName" />
    <input id="txtCompanyName" type="text" value="txtCompanyName" />
</div>
<div>
    <button onclick="SaveDocumentData()">submit</button>
</div>

<script type="text/javascript">
    function SaveDocumentData() {
        debugger;
        var formData = new FormData();
        var attachment = $('#AttachmentFile').val();
        if (attachment)
        {
            formData.append("attachmentFile",$('#AttachmentFile')[0].files[0]);
        }
        $.each(getDocumentObject(), function(key, value){
          formData.append("healthCard." key, value);
        })
        $.each(getEmploymentHistory(), function(key, value){
          formData.append("empHistory." key, value);
        })
        
        $.ajax({
            url: '/Home/Test',
            data: formData ,
            dataType: 'json',
            type: 'POST',
            cache: false,
            async: false,
            processData: false,
            contentType: false,
            success: function (data) {
                alert("success");
            },
            error: function (data) {
                return data;
            }
        })
    }

    function getDocumentObject() {
        var object = new Object();
        object.IssueDate = $('#IssueDate').val();
        object.Title = $('#DocumentTitle').val();
        object.HealthCardId = $('#HealthCardId').val();
        return object;
    }

    function getEmploymentHistory()
    {
        var object = new Object();
        object.Title = $('#cmdTitle').val();
        object.NameSupervisor = $('#txtSupervisorName').val();
        object.CompanyName = $('#txtCompanyName').val();
        return object;
    }
</script>

Test Result: enter image description here

  • Related