简体   繁体   English

如何使用ajax jquery将多个对象从视图发布到dot net core 6 MVC控制器

[英]How To Post Multiple Objects from View To dot net core 6 MVC Controller using ajax jquery

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这是我的 ViewModel 类

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

You're manually building a JSON string containing another JSON string, which is the root cause of your problem.您正在手动构建一个包含另一个 JSON 字符串的 JSON 字符串,这是问题的根本原因。 To fix this provide a plain JS object to the data property of the $.ajax() invocation.要解决此问题,请为$.ajax()调用的data属性提供一个普通的 JS 对象。

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!');
    }
  });
}

Here is a working demo to pass json type data to action with ajax:这是一个使用 ajax 将 json 类型数据传递给操作的工作演示:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用jQuery AJAX将多个变量POST到ASP .NET MVC控制器 - Using jQuery AJAX to POST multiple variables to an ASP .NET MVC Controller 如何将对象添加到视图中的列表并将修改后的列表发布回控制器? (ASP .NET 核心 wirth mvc) - How to add objects to list in view and post modified list back to controller? (ASP .NET core wirth mvc) 如何使用 AJAX POST 对象并使用 ASP.NET Core MVC 控制器获取? - How to POST object using AJAX and get with ASP.NET Core MVC controller? 在 C# ASP.NET Core MVC 中使用 AJAX 将数据从视图传递到控制器 - Pass data from view to controller using AJAX in C# ASP.NET Core MVC 从视图向控制器传递.Net Core中的多个复杂对象 - Passing Multiple Complex Objects in .Net Core From View To Controller MVC4控制器将多个json对象发布到控制器,ajax发布 - MVC4 controller post multiple json objects to controller, ajax post .net core 3.1 将 ajax 对象列表发布到 MVC 控制器没有数据到达 - .net core 3.1 post ajax list of objects to MVC controller no data arriving 如何通过Jquery.ajax()将字符串值从视图传递到ASP.NET MVC控制器 - How to pass string value from a view via Jquery.ajax() to ASP.NET MVC controller 如何使用AJAX将数据发布到ASP.NET MVC控制器? - How to post data to ASP.NET MVC controller using AJAX? ASP.NET Core MVC Ajax发布到具有多个参数的控制器返回错误的请求 - Asp.net core mvc ajax post to controller with multiple parameters return bad request
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM