从Ajax到MVC动作获取数据

max*_*986 5 javascript c# ajax asp.net-mvc jquery

我想将对象数组从ajax调用发送到控制器操作。

在后端,我有

容器类:

public class MyContainer
{
    public string Id { get; set; }
    public Filter[] Filters { get; set; }
}

public class Filter
{
    public string Name { get; set; }
    public string[] Values { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

和动作:

public ActionResult MyAction(MyContainer container)
{
   var id = container.Id;
   foreach(Filter filter in container.Filters)
   {
       //Do something
   }
}
Run Code Online (Sandbox Code Playgroud)

在前端,我有

$(document).on('click', 'mySelector', function (event) {

    //Create first object
    var firstIds = {};
    firstIds.Name = "Custom Name 1";
    firstIds.Values = GetIds('param1'); //this return an array of strings

    //Create second object
    var secondIds = {};
    secondIds.Name = "Custome Name 2";
    secondIds.Values = GetIds('param2'); //another array

    var Id = $(this).attr('id'); //id of element

    //Add objects to array
    var filters = [];
    filters.push(firstIds);
    filters.push(secondIds);

    $.ajax({
        method: "GET",
        url: baseUrl+"/MyAction",
        //traditional: true, //I tried with and without that parameter
        data:
        {
            Id: Id,
            Filters: filters
        },
        contentType: 'application/json',
        success: function (res) {
            alert('success')
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

因此,如果我像在上面的示例中那样使用它,则正在运行的容器对象具有Id值,并且在Filters中具有2个元素的数组,但是它们两个的Name和Values均为null。

在将传统设置为True的情况下,我设置了container.Id,但container.Filters = null。

有什么建议吗?谢谢。

Mih*_*nut 5

POST请求与JSON.stringify()方法结合使用。

C#

[HttpPost]
public ActionResult MyAction(MyContainer container)
{
   var id = container.Id;
   foreach(Filter filter in container.Filters)
   {
       //Do something
   }
}
Run Code Online (Sandbox Code Playgroud)

JQUERY

$.ajax({
    method: "POST",
    url: baseUrl+"/MyAction",
    data:JSON.stringify(
    {
        Id: Id,
        Filters: filters
    }),
    contentType: 'application/json',
    success: function (res) {
        alert('success')
    }
});
Run Code Online (Sandbox Code Playgroud)

为什么需要JSON.stringify()方法?

contentType是您要发送的数据类型,因此application/json;默认值为application/x-www-form-urlencoded; charset=UTF-8.

如果使用application/json,则必须使用JSON.stringify()才能发送JSON对象。

JSON.stringify()将JavaScript 对象转换json文本并将其存储在中string