javascript - 将 JavaScript 对象传递给 Controller

标签 javascript c# ajax .net-core

我正在尝试使用 JavaScript 将对象传递给 Controller ​​。

我使用了两个参数 _amount_total 但是 回发时 Controller 中的值是空的。 为什么我无法获得值(value)的任何想法? 另外,如果我想获取 _data 这是一个包含不同的对象 值(value)观,我将如何实现它?

var itemsCart=toys.cart._items;

$.ajax({
  url: '@Url.Action("SuccessView", "Home")',
  type: 'POST',
  data:  itemsCart,
  success: function (response) {
    alert(response);
  },
  error: function (xhr, ajaxOptions, throwError) {
    alert(xhr.responseText);
  }
});

Controller :

public IActionResult SuccessView(List<ProductViewModel> products)
  {
    return View();
  }

查看模型:

public class ProductViewModel
  {
    public string _amount { set; get; }
    public string _total { set; get; }
  }

以及来自网站的对象截图:

enter image description here

最佳答案

听起来问题是您的参数声明为 products,但您的 AJAX data 参数名称与 Controller 操作参数名称不匹配。尝试改用此设置:

JS

$.ajax({
     url: '@Url.Action("SuccessView", "Home")',
     type: 'POST',
     data: { products: itemsCart },
     traditional: true,
     success: function (response) {
         alert(response);
     },
     error: function (xhr, ajaxOptions, throwError) {
         alert(xhr.responseText);
     }
});

Controller Action

[HttpPost]
public IActionResult SuccessView([FromBody] List<ProductViewModel> products)
{
    // do something

    return new JsonResult("OK");
}

请注意,由于您的 AJAX 调用定义为 type: POST,因此您必须将 [HttpPost] 属性应用于 Controller 操作。

相关问题:

Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

关于javascript - 将 JavaScript 对象传递给 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53941191/

相关文章:

c# - Html.EnumDropdownListFor : Showing a default text

c# - 在 Windows 8 中将 BitmapImage 对象保存为本地存储中的文件?

php - Mysql 查询在编辑的 jTable 代码中不起作用,为什么?

javascript - 在没有 getJSON 的情况下从 Javascript 中的枚举 JSON 子数组中检索数据

javascript - 如何使用ajax刷新动态生成的div?

javascript - jquery Accordion 改变文本

javascript - 将箭头指向位置(地理位置)

c# - UWP AppServiceConnection 没有获得值(value)

javascript - Google One-tap 声明全局变量 L

javascript - Jquery 文件上传插件无法在 Internet Explorer 11 中拖放文件