您好我是JavaScript和MVC的新手,我正在尝试将List和字符串传递给我的控制器。
JavaScript看起来像:
var parms = {
globalList: globalList,
fieldName: fieldName
};
$.ajax({
//contentType: 'application/json; charset=utf-8',
type: "POST",
traditional: true,
url: "/Home/SaveField",
async: false,
data: parms,
dataType: "json",
success: function (data) {
console.log("uspjeh");
},
error: function (errorData) {
console.log("errors");
}
});
});
和控制器看起来像:
public void SaveField(List<Point> globalList, String fieldName)
{
// filedName is correctly passed
// list is null
}
请问有人能帮帮我吗?
点类:
public class Point
{
[Key]
public int PointId { get; set; }
public float GeoDuzina { get; set; }
public float GeoSirina { get; set; }
[ForeignKey("Data")]
public int DataId { get; set; }
public virtual Data Data { get; set; }
}
答案 0 :(得分:0)
它不会工作。如果您稍微调试一下,您将看到您向服务器发布如下内容:
globalList:[object Object]
globalList:[object Object]
globalList:[object Object]
它只是字符串数组。但有一种方法可以做你想要的。 您可以将数组序列化为json,然后在控制器中反序列化它。只需将您的参数更改为:
var parms = {
globalList: JSON.stringify(globalList),
fieldName: fieldName
};
行动:
[HttpPost]
public void SaveField(string globalList, string fieldName)
{
var serializer = new JavaScriptSerializer(); //use any serializer you want
var list = serializer.Deserialize<List<Point>>(globalList);
}
或者您可以从HTML表单中创建param对象:
var parms = {
"globalList[0].GeoDuzina": 51.506760996586294,
"globalList[0].GeoSirina": -0.06106463202740998,
"globalList[1].GeoDuzina": 51.516269286402846,
"globalList[1].GeoSirina": -0.056258113472722464,
"globalList[2].GeoDuzina": 51.50419662363912,
"globalList[2].GeoSirina": -0.044413478462956846,
fieldName: fieldName
};
它适用于您的行动。
还有很多其他方法可以做到这一点。我只展示其中两个。对你有好处吗?
顺便说一句。对于花车,这个数字太长了。;)