pass array in javascript object to mvc controller

霸气de小男生 提交于 2021-01-28 23:19:50

问题


I have a javascript object like:

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

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

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; }

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


回答1:


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

Note that traditional:true on the jquery ajax call:

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;.

Source: jQuery.param() Docs

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

Controller/Model

[HttpPost]
public void PostManager(Data  data)
{

}

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


来源:https://stackoverflow.com/questions/34131308/pass-array-in-javascript-object-to-mvc-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!