Skip to main content
 首页 » 编程设计

javascript之使用 AJAX 将数组发布到 MVC C#

2024年02月25日36artech

我正在尝试将数组发布到我的 MVC 操作,但我仍然收到空值。

    //Send List of services to controller 
$('#submitButton').click(function () { 
    $.ajax({ 
        contentType: 'application/json; charset=utf-8', 
        dataType: 'json', 
        type: 'GET', 
        url: '/Appointments/GetListOfServices', 
        data: JSON.stringify({ CheckedItems: checkedItems }), 
        traditional: true, 
        success: function (data) { 
            alert(data.Result); 
        }, 
        failure: function (response) { 
            $('#result').html(response); 
            console.log("failed"); 
        } 
    });  
}); 

当我调用 GetListOfServices 函数时,我收到一个空值

        public JsonResult GetListOfServices(int[] CheckedItems) 
    { 
        Console.WriteLine(CheckedItems); 
        return Json(new { message= "OK" }); 
    } 

当我在浏览器中检查控制台和“网络”选项卡时,它显示以下内容:

请您参考如下方法:

首先你应该考虑的是,如果数组内容很大,那么数组内容可能会超过查询字符串限制,因此你可以尝试使用 POST 方法代替。如果要将数组作为 Controller 操作参数传递,则需要在 AJAX 调用中设置 traditional: true 选项:

$('#submitButton').click(function () { 
    $.ajax({ 
        dataType: 'json', 
        type: 'GET' // or 'POST' 
        traditional: true, 
        url: '/Appointments/GetListOfServices', 
        data: { CheckedItems: checkedItems }, 
        traditional: true, 
        success: function (data) { 
            alert(data.message); 
        }, 
        failure: function (response) { 
            $('#result').html(response); 
            console.log("failed"); 
        } 
    });  
}); 

作为替代方案,您可以使用 $.param() 并将 traditional 属性设置为 true:

$('#submitButton').click(function () { 
    $.ajax({ 
        dataType: 'json', 
        type: 'GET', // or 'POST' 
        url: '/Appointments/GetListOfServices', 
        data: $.param({ CheckedItems: checkedItems }, true), 
        success: function (data) { 
            alert(data.message); 
        }, 
        failure: function (response) { 
            $('#result').html(response); 
            console.log("failed"); 
        } 
    });  
}); 

最后,不要忘记通过添加 [HttpPost] 属性将 JsonResult 操作标记为 POST 方法 重新使用 POST:

[HttpPost] 
public JsonResult GetListOfServices(int[] CheckedItems) 
{ 
    Console.WriteLine(CheckedItems); 
    return Json(new { message= "OK" }); 
} 

如果您使用的是 GET,请确保设置了 JsonRequestBehavior.AllowGet:

public JsonResult GetListOfServices(int[] CheckedItems) 
{ 
    Console.WriteLine(CheckedItems); 
    return Json(new { message= "OK" }, JsonRequestBehavior.AllowGet); 
} 

注意:您可以使用 jQuery.getJson() 尝试更短的语法,但仍然需要 traditional: true 选项:

$.getJSON('/Appointments/GetListOfServices', $.param({ CheckedItems: checkedItems }, true), function (data) { 
    alert(data.message); 
}); 

使用此设置,数组应该作为操作方法参数正确接收。