我有多个参数,我必须传递给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”&的值。其他价值观没有到来。 e.g。
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"]];["
其他价值观尚未到来。 我在这里做错了。
答案 0 :(得分:2)
我担心你的网址太长(> 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
}
我看到你正在为routeInfo使用二维数组。但是只有一个项目,我认为您应该将其更改为1维数组,以使其与控制器代码string[] routeInfo
答案 1 :(得分:2)
此处输入的网址信息太多,不仅仅是您没有正确地将参数附加到一起,而是需要使用&
而不是;
将其分开。
最重要的是,你并没有真正利用MVC功能。在客户端,您希望将您的信息作为集体对象而不是单个参数发送,例如
var schoolRoutes = {
routes: routes,
colors: colorsArray,
times: mytimeArray,
distances: myDistanceArray,
direction: $("#Direction").val()
};
$.ajax({
type: 'POST'
url: "api/HomeToSchoolRoutes",
data: JSON.stringify(schoolRoutes),
dataType: "json",
success: function (data) {
if (data = true) {
alert("Routes Saved Successfully");
}
else if (data = false) {
alert("Routes are not saved");
}
});
然后在服务器端,引入一个能够绑定到传入数据的类,即ViewModel
public class RouteInfoViewModel
{
...
}
public class SchoolRoutesViewModel
{
public RouteInfoViewModel[] Routes { get; set; }
public string[] Colours { get; set; }
public double[] Times { get; set; }
public double[] Distances { get; set; }
public string Direction { get; set; }
}
然后更新您的操作以期望此特定ViewModel
,这样您就可以访问所有已发布的信息。
public bool PostHomeToSchoolRoutes(SchoolRoutesViewModel schoolRoutes)
{
...
}