我有多个参数必须传递给api控制器。

我在做什么

在我的JavaScript中

            var routeInfo = JSON.stringify(routes);
            var colors = JSON.stringify(colorsArray);
            var times = JSON.stringify(mytimeArray);
            var distances = JSON.stringify(myDistancArray);
            var dir = $("#Direction").val();

          var fullString = routeInfo + ";" + colors + ";" + times + ";" + distances+";"+dir;

            $.post("api/HomeToSchool/?route=" + fullString,
                function (data) {
                    if (data = true) {
                        alert("Routes Saved Successfully");
                    }
                    else if (data = false) {
                        alert("Routes are not saved");
                    }
                });


和在我的控制器中

public bool PostHomeToSchoolRoutes([FromUri]string route)
        {
// my logic
}


在这里,我只是获取“ routeInfo”的值,而其他值未出现。
例如

var routeInfo =  [["Børge,Brogade  38, 4100, Ringsted,09:25:00,55.43953, 11.79043","Grete,Sjællandsgade  27, 4100, Ringsted,09:25:00,55.44024, 11.78852","Else,Fynsgade  14, 4100, Ringsted,09:25:00,55.44128, 11.78595","Birthe,Eksercerpladsen  47, 4100, Ringsted,09:25:00,55.44954, 11.80309","Knud Lavard Centret, Eksercerpladsen 3,  4100,  Ringsted,370,55.45014, 11.80474"]]

                var colors = ["#886A52"]
                var times =  [7.97]
                var distances = [3.36]
                var dir = 0


我在控制器中得到的是

[["Børge,Brogade  38, 4100, Ringsted,09:25:00,55.43953, 11.79043","Grete,Sjællandsgade  27, 4100, Ringsted,09:25:00,55.44024, 11.78852","Else,Fynsgade  14, 4100, Ringsted,09:25:00,55.44128, 11.78595","Birthe,Eksercerpladsen  47, 4100, Ringsted,09:25:00,55.44954, 11.80309","Knud Lavard Centret, Eksercerpladsen 3,  4100,  Ringsted,370,55.45014, 11.80474"]];["


其他值不来了。
我在这里做什么错。

最佳答案

恐怕您的网址太长(> 255个字符),您可以尝试一下。

$.ajax({
     type: 'POST',
     url:"api/HomeToSchool",
     data:{routeInfo:routes,colors:colorsArray,times:mytimeArray,distances:myDistancArray,dir:dir},
     dataType: "json",
     traditional:true,
     function (data) {
                        if (data = true) {
                            alert("Routes Saved Successfully");
                        }
                        else if (data = false) {
                            alert("Routes are not saved");
                        }
                    }
});


和您的控制器:

public bool PostHomeToSchoolRoutes(string[] routeInfo,string[] colors,double[] times,double[] distances,int dir)
        {
// my logic
}


我看到您正在使用2维数组作为routeInfo。但是只有一项,我认为您应该将其更改为一维数组以使其与控制器代码string[] routeInfo兼容

关于javascript - 如何从 View 向mvc4中的api Controller 发送多个参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16252132/

10-11 06:08