将javascript对象中的数组传递给mvc控制器 [英] pass array in javascript object to mvc controller

查看:77
本文介绍了将javascript对象中的数组传递给mvc控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的javascript对象:

I have a javascript object like:

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

如您所见,name和id是简单的字符串,而EmployeeNames是一个数组对象.我有这样的ajax呼叫:

As you can see, name and id are simple strings but EmployeeNames is an array object. I have the ajax call like this:

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

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

In the controller I have a method GetManagerEmployees(Data data) with parameter of type Data which contains all the properties:

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

我在控制器中获取data.EmployeeNames为null,这是怎么回事?你能帮我吗?

I'm getting data.EmployeeNames as null in my controller, what am I doing wrong here? Can you please help me on this?

推荐答案

仅使用此结构创建了一个项目,并且可以正常工作:

Just created a project with this structure and It's working:

请注意,jquery ajax调用上的radius:true:

Note that traditional:true on the jquery ajax call:

从jQuery 1.4开始,$ .param()方法以递归方式对深层对象进行序列化,以适应现代脚本语言和框架,例如PHP和Ruby on Rails.您可以通过设置jQuery.ajaxSettings.traditional = 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()文档

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

Also, you don't need a List for that. Just use a simple string array in your model.

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

控制器/型号

[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对象中的数组传递给mvc控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆