在ASP.NET MVC 3中,我没有运气试图将JSON数据发送到我的控制器。
我循环遍历列表并从元素生成JSON对象,然后将它们与我的查询参数一起发送:
$.each(addedIngredients.find('li'), function () {
ingredients[count] = {
ID: $(this).attr('id').split('_')[1],
Name: $(this).attr('id').split('_')[0]
};
count++;
});
request = $.ajax({
url: '/Ingredients/SearchIngredients',
data: {
q: q,
ingredients: ingredients
},
dataType: 'json',
type: 'POST',
success: function (result) {
//Code omitted
},
error: function () {
//Code omitted
}
});
在控制器上我有
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult SearchIngredients(string q, JSONIngredient[] ingredients)
{
//Initialise model
List<JSONIngredient> model = new List<JSONIngredient>();
//Add items to list
ir.GetIngredients(q).ToList().ForEach(i => model.Add(new JSONIngredient(i)));
//Return model as JSON object
return this.Json(model);
}
JSONingredient在哪里
public class JSONIngredient
{
public int ID { get; set; }
public string Name { get; set; }
public JSONIngredient()
{
}
public JSONIngredient(Ingredient Ingredient)
{
this.ID = Ingredient.ID;
this.Name = Ingredient.Name;
}
}
我之所以编造,是因为我认为我的普通模型具有不在JSON中的其他属性导致了问题,但我想如果它确实有效,它将适用于我的普通模型... < / p>
我在想,我发送数据的格式可能不正确。在firefox中检查请求显示:
Parametersapplication / X WWW的窗体-urlencoded 成分[0] [ID] 4 成分[0] [名称]水 q sug
来源
Q =&SUG放大器;成分%5B0%5D%5BName%5D =水和安培;成分%5B0%5D%5BID%5D = 4
非常感谢任何帮助。
答案 0 :(得分:0)
在摆弄了一段时间并尝试了这个之后我终于开始工作了。我怀疑数据格式不正确。而不是发送纯JSON对象
data: {
q: q,
ingredients: ingredients
}
我需要发送一个字符串化的对象:
JSON.stringify({ q: q, ingredients: ingredients})
当你知道它时很简单。
答案 1 :(得分:0)
围绕您的数据调用JSON.stringify。 请看这里的例子: Post an Array of Objects via JSON to ASP.Net MVC3
首先尝试'q',然后尝试只是'成分'