将数据数组从Javascript传递到C#
这是我的班级:将数据数组从Javascript传递到C#,c#,javascript,ajax,asp.net-mvc,C#,Javascript,Ajax,Asp.net Mvc,这是我的班级: public class ARecipe { public string picture { get; set; } public string title { get; set; } public int cookingTime { get; set; } public int preparationTime { get; set; } public string IngredientList { get; set; } publ
public class ARecipe
{
public string picture { get; set; }
public string title { get; set; }
public int cookingTime { get; set; }
public int preparationTime { get; set; }
public string IngredientList { get; set; }
public string ingredientsDescription { get; set; }
public int nbPersons { get; set; }
public string Category { get; set; }
public string difficulty { get; set; }
public double nbStars { get; set; }
}
我的Ajax调用:
var dico = {
picture: $("#fakeInput").val(),
title : $("#title").val(),
cookingTime : $("#cookingTime").val(),
preparationTime : $("#preparationTime").val(),
IngredientList : $("#ingredientListArea").val(),
ingredientsDescription : $("#preparationArea").val(),
nbPersons : parseInt($("#select-nb-Persons").val()),
Category : $("#select-category").val(),
difficulty: $("#select-difficulty").val(),
nbStars : 4
};
$.ajax({
url: "/AddRecipe/TempData",
type: 'POST',
success: function (e) {
//success event
},
///Form data
data: JSON.stringify(dico),
///Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: false,
processData: false
});
以及接收数据的方法:
[HttpPost]
public ActionResult TempData(ARecipe recipe) {
return Json("");
}
我的Ajax调用会转到TempData方法,但是当我使用调试器分析参数“recipe”时,我注意到所有字段都是“null”
为什么?
你有解决办法吗
谢谢您将以JSON的形式发送数据,但服务器希望以常规POST数据的形式发送数据。只需让
ajax
方法将其转换为常规POST请求,而不是将其强制转换为JSON:
///Form data
data: dico,
只要纠正这些问题:
$.ajax({
url: "/AddRecipe/TempData",
type: 'POST',
dataType: 'json',
contentType: 'application/json',
success: function (e) {
//success event
},
///Form data
data: JSON.stringify(dico),
///Options to tell JQuery not to process data or worry about content-type
cache: false,
});
[HttpPost]
public JsonResult TempData(ARecipe recipe) {
return Json("");
}
指定dataType:'json'和contentType:'application/json',您可以尝试一下
data:dico,
?