如何通过ajax调用将数组作为参数从View传递给MVC控制器?

时间:2014-03-03 00:38:14

标签: ajax asp.net-mvc

我有一个接受数组的控制器,如果我使用下面的Html.ActionLink,则返回它应该的视图:

 @Html.ActionLink("Advanced Search Test", "ReqsSummary",routeValues: new{ReqDepartment= "Facilities",EquipmentGroup="Vehicles",SiteCode="LUR"})

我最终将在阵列中拥有大约20个参数。我尝试过一些不同的方式配置ajax调用,但是我传递的数据数组中的值永远不会到达控制器。我在View上使用MVVM模式。这是我正在努力工作的viewModel中的函数。在ajax调用之前正在正确填充数据数组,这不是问题:

 submit: function () {
        var data = {
            "ReqDepartment": (viewModel.reqDepartment === null) ? null : viewModel.reqDepartment,
            "EquipmentGroup": (viewModel.equipmentGroup === null) ? null : viewModel.equipmentGroup,
            "SiteCode": (viewModel.site === null) ? null : viewModel.site.SiteCode,
        }; //header

        var criteria = JSON.stringify(data);
        $.ajax({
                type: "POST",
                url: "/ArctecLogisticsWebApp/Requisitions/ReqsSummary/?",
                data: criteria,
                traditional: true

         });

控制器:

public ViewResult ReqsSummary(ReqSearchCriteria criteria)
    {
        return View("ReqsSummary", requisitionsRepository.GetReqsAdvancedSearch(criteria));
        //This works when I use the  Html.ActionLink shown above. 
    }

ViewModel ReqSearchCriteria:

 public class ReqSearchCriteria
{
    public string ReqDepartment { get; set; }
    public string EquipmentGroup { get; set; }
    public string SiteCode { get; set; }

}   

1 个答案:

答案 0 :(得分:0)

您不需要对数据对象进行字符串化,默认的Model Binder将处理JSON对象绑定而无需进行字符串化。

submit: function () {
    var data = {
        "ReqDepartment": (viewModel.reqDepartment === null) ? null : viewModel.reqDepartment,
        "EquipmentGroup": (viewModel.equipmentGroup === null) ? null : viewModel.equipmentGroup,
        "SiteCode": (viewModel.site === null) ? null : viewModel.site.SiteCode,
    }; //header

    $.ajax({
            type: "POST",
            url: "/ArctecLogisticsWebApp/Requisitions/ReqsSummary/",
            data: data,
            traditional: true

     });
}