0

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

2 Answers 2

1

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!');
    }
  });
}
Sign up to request clarification or add additional context in comments.

4 Comments

Will implement and come back to you Thanks in advance
well thanks for ur help but it still not binding emailvm and invoicevm in controller
The root object allSettings doesn't need to be named in the json; data: { InvoicesVM: InvoicesVM, EmailVM: EmailVM } But you will need [FromBody].
@JeremyLakeman thanks for pointing that out -not sure how I missed it!
0

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("");
        }

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.