javascript - 将 javascript 对象中的数组传递给 mvc Controller

标签 javascript jquery ajax asp.net-mvc

我有一个 JavaScript 对象,例如:

var data={
 Manager:name,
 ID:id,
 EmployeeNames:arrayEmployees
};

如您所见,name 和 id 是简单的字符串,但 EmployeeNames 是一个数组对象。我有这样的 ajax 调用:

 $.ajax({
      type: "POST",
      url: "GetManagerEmployees",
      content: "application/json;",
      dataType: "json",
      data: data,
      success: 
      error: 
});

在 Controller 中,我有一个方法 GetManagerEmployees(Data data) ,其参数类型为 Data,其中包含所有属性:

public class Data
{
    public string Manager { get; set; }
    public int id { get; set; }
    public List<string> EmployeeNames { get; set; }

我在 Controller 中获取 data.EmployeeNames 为 null,我在这里做错了什么?你能帮我解决这个问题吗?

最佳答案

刚刚创建了一个具有此结构的项目并且它正在运行:

请注意 jquery ajax 调用中的传统:true:

As of jQuery 1.4, the $.param() method serializes deep objects recursively to accommodate modern scripting languages and frameworks such as PHP and Ruby on Rails. You can disable this functionality globally by setting jQuery.ajaxSettings.traditional = true;.

来源:jQuery.param() Docs

此外,您不需要列表。只需在模型中使用一个简单的字符串数组即可。

Javascript

$("#myBtn").click(function () {

                var arrayEmployees = new Array();

                arrayEmployees.push("Name1");

                var data = {
                    "Manager": 'John',
                    "id": 1,
                    "EmployeeNames": arrayEmployees
                };

                $.ajax({
                    type: "POST",
                    traditional:true,
                    url: "PostManager",
                    content: "application/json;",
                    dataType: "json",
                    data: data,
                    success: function () {
                    }
                });
            });

Controller /模型

[HttpPost]
public void PostManager(Data  data)
{

}

public class Data
{
    public string Manager { get; set; }
    public int id { get; set; }
    public string[] EmployeeNames { get; set; }
}

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

相关文章:

javascript - 未捕获的异常 : cannot call methods on tabs prior to initialization

jquery - 加载搜索引擎友好的页面片段

javascript - 发送此 AJAX Post 数据的正确内容类型

javascript - 联系表单 7 根据下拉选择将页面重定向到特定 URL

javascript - jQuery 创建元素名称

javascript - jQuery 风格 : when is it better to use a var for multiple operations?

php - datatables.net 列对另一列进行排序

javascript - 从 Node.js 更新 MySQL - 如何判断零行是否受到影响?

javascript - 从 HTML 输出中获取特定值

javascript - Div 元素充当背景