jquery - 我如何将对象数组从js发送到服务器?

标签 jquery .net asp.net-mvc json

我的类(class)

[Serializable]
    public class VSpecialQualifiers
    {
        public VCD LivingStatus { get; set; }
        public VCD Relationship { get; set; }
        public string OnSetAge { get; set; }
    }

我的js函数

 $.ajax({
                url: url,
                type: 'POST',
                datatype: 'json',
                data: {
                   'arr' : self.specialQualifiers
                }
          });

我的服务器方法

[HttpPost]
        public JSONResult SaveProblem(object[] arr)
        {
          //i cant't cast to target type
        }

如何将对象数组从 js 传递到服务器?

最佳答案

这里有一些对我有用的东西(后端的 C# MVC)。

...在js中:

var viewModel = new Object();
viewModel.Items = items; // items is a js array of objects
$.ajax({
    data: JSON.stringify(viewModel),
    type: "POST",
    contentType: 'application/json; charset=utf-8',
    cache: false,
    url: 'CONTROLLERNAME/ACTIONNAME', // replace as necessary here
    success: function (data) {
       // handle the return value, if any, here
    }
});

...在 Controller 中,这里的签名才是最重要的:

[HttpPost]
public ActionResult ACTIONNAME(WorksheetVM inputModel) {

...这是一个关联的 ViewModel 定义,其中 WorksheetItemVM 是 View 模型 DTO,其中包含传递的每个 Js 对象的字段列表:

public class WorksheetVM {
    public WorksheetItemVM[] Items { get; set; }
}

关于jquery - 我如何将对象数组从js发送到服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6442789/

相关文章:

jQuery 自定义保管箱 : how to tabindex

javascript - 在 Laravel 中刷新页面时删除 jQuery 中的 cookie

c# - 此 WCF 配置是否导致我的 400 错误请求?

c# - 解析是获取成员类型的唯一方法吗?

c# - EF CORE 无时间戳乐观并发

c# - 如何确定 PropertyType 是否为外键

asp.net-mvc - 随机发生的 Ninject 异常 : "Error loading Ninject component ICache"

jQuery 验证 : multiple form, 单次验证

javascript - 子菜单部分显示

jquery - 更改 jqGrid 中的单元格文本