Home > Net >  How To Post Multiple Objects from View To dot net core 6 MVC Controller using ajax jquery
How To Post Multiple Objects from View To dot net core 6 MVC Controller using ajax jquery

Time:06-06

I have tried to solve the issue but I cannot figure it out I don't know what a problem in my code I want to post this form with the objects tell me what I'm missing in it any help will be appreciated! Here is my script

 function getInvoiceObject() 
      {
    var Invoice = new Object();
    //var form = $('#Invoice-Form')[0];
    //const formData = new FormData(form);
    Invoice.InvoiceId = $('#InvoiceId').val();
    Invoice.InvoiceTemplateId = $('#InvoiceTemplateId').val();
    Invoice.InvoiceDueAfterDays = $('#InvoiceDueAfterDays').val();
    Invoice.DefulatTerms = $('#DefulatTerms').val();
    Invoice.DefaultFooter = $('#DefaultFooter').val();
    return Invoice;
      }
      
      function getEmailObject() 
      {
          var Email = new Object();
          Email.EmailId = $('#EmailId').val();
          Email.InvoiceEmailBody = $('#InvoiceEmailBody').val();
          Email.OverDueInvoiceEmailBody = $('#OverDueInvoiceEmailBody').val();
         return Email;
      }
      

      function SaveAllSettings()
      {
debugger;
          var InvoicesVM = getInvoiceObject();
          var EmailVM    = getEmailObject();
         // var AllSettings = [];
         // AllSettings.push(Invoices);
         // AllSettings.push(Email);
           var AllSettings = {InvoicesVM:InvoicesVM, EmailVM: EmailVM};
           //console.log(postData);
          $.ajax({
                //dataType: 'json',
               // async: true,
                type: 'POST',
                url: "/Settings/SaveAllSettings",              
                data: '{ "AllSettings":'   JSON.stringify(AllSettings)   '}', 
                processData: false,
                traditional: true,
                cache: false,
                contentType: "application/json; charset=utf-8",  
                dataType: "json", 
                success: function (response) {
                  toastr.success('Saved SuccessFully!');
                },
                error: function (msg) {
                  //toastr.error('Cannot Save the Data!');
                }
            })

      }

And here is my Controller

           
        [HttpPost]
       public JsonResult SaveAllSettings(SettingsVM AllSettings)
        {
           
            return Json("");
        }

And here is my ViewModel class

 public class SettingsVM
    {
        public InvoiceSettingsVM InvoicesVM { get; set; }
        public EmailSettingsVM EmailVM { get; set; }
    }

CodePudding user response:

You're manually building a JSON string containing another JSON string, which is the root cause of your problem. To fix this provide a plain JS object to the data property of the $.ajax() invocation.

data: { 
  InvoicesVM: InvoicesVM, 
  EmailVM: EmailVM
}, 

Here's a complete example with a few other syntax/good practice improvements:

let getInvoiceObject = () => ({
  invoiceId = $('#InvoiceId').val(),
  invoiceTemplateId = $('#InvoiceTemplateId').val(),
  invoiceDueAfterDays = $('#InvoiceDueAfterDays').val(),
  defulatTerms = $('#DefulatTerms').val(), // typo in property name/element id here...?
  defaultFooter = $('#DefaultFooter').val(),
})

let getEmailObject = () => ({
  emailId = $('#EmailId').val(),
  invoiceEmailBody = $('#InvoiceEmailBody').val(),
  overDueInvoiceEmailBody = $('#OverDueInvoiceEmailBody').val(),
})

let saveAllSettings = () => {
  $.ajax({
    type: 'POST',
    url: "/Settings/SaveAllSettings",
    dataType: "json",
    data: { 
      invoicesVM: getInvoiceObject(), 
      emailVM: getEmailObject()
    }, 
    traditional: true, // probably not needed here
    cache: false,
    success: function(response) {
      toastr.success('Saved SuccessFully!');
    },
    error: function(msg) {
      //toastr.error('Cannot Save the Data!');
    }
  });
}

CodePudding user response:

Here is a working demo to pass json type data to action with ajax:

js:

function getInvoiceObject() 
      {
    var Invoice = new Object();
    //var form = $('#Invoice-Form')[0];
    //const formData = new FormData(form);
    Invoice.InvoiceId = $('#InvoiceId').val();
    Invoice.InvoiceTemplateId = $('#InvoiceTemplateId').val();
    Invoice.InvoiceDueAfterDays = $('#InvoiceDueAfterDays').val();
    Invoice.DefulatTerms = $('#DefulatTerms').val();
    Invoice.DefaultFooter = $('#DefaultFooter').val();
    return Invoice;
      }
      
      function getEmailObject() 
      {
          var Email = new Object();
          Email.EmailId = $('#EmailId').val();
          Email.InvoiceEmailBody = $('#InvoiceEmailBody').val();
          Email.OverDueInvoiceEmailBody = $('#OverDueInvoiceEmailBody').val();
         return Email;
      }
      

      function SaveAllSettings()
      {
debugger;
          var InvoicesVM = getInvoiceObject();
          var EmailVM    = getEmailObject();
         // var AllSettings = [];
         // AllSettings.push(Invoices);
         // AllSettings.push(Email);
           var AllSettings = {InvoicesVM:InvoicesVM, EmailVM: EmailVM};
           //console.log(postData);
          $.ajax({
                //dataType: 'json',
               // async: true,
                type: 'POST',
                url: "/Settings/SaveAllSettings",              
                data: JSON.stringify(AllSettings),
                contentType: "application/json; charset=utf-8",  
                dataType: "json", 
                success: function (response) {
                  toastr.success('Saved SuccessFully!');
                },
                error: function (msg) {
                  //toastr.error('Cannot Save the Data!');
                }
            })

      }

action:

[HttpPost]
       public JsonResult SaveAllSettings([FromBody]SettingsVM AllSettings)
        {
           
            return Json("");
        }
  • Related