无法将JSON数据发送到asp.net MVC控制器
在ASP.NET MVC 3中,我没有尝试将JSON数据发送到我的控制器。通过列表无法将JSON数据发送到asp.net MVC控制器
我环路和生成的元素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的属性导致了这个问题,但我会认为,如果它确实工作,它将适用于我的正常模型...
我在想也许我发送的格式数据不正确。检查在Firefox显示请求:
Parametersapplication/X WWW的窗体-urlencoded 成分[0] [ID] 4种 成分[0] [名称]水 q SUG
源
q = sug &成分%5B0%5D%5B名称%5D =水&成分%5B0%5D%5BID%5D = 4
任何帮助将不胜感激。
调用JSON.stringify围绕您的数据。 见这里的一个例子: Post an Array of Objects via JSON to ASP.Net MVC3
首先尝试只用“Q”,然后尝试刚才“成分”
经过一段时间的摆弄和尝试这一点后,我终于得到它的工作。正如我怀疑数据格式不正确。而不是发送一个纯粹的JSON对象
data: {
q: q,
ingredients: ingredients
}
的,我需要发送一个字符串化的对象:当你知道它
JSON.stringify({ q: q, ingredients: ingredients})
简单。
不错,我刚刚发布ha就发了:) – 2012-02-23 07:01:22
是的,刚才看到了,对不起。但既然你花时间回复我会给你答案。 – 2012-02-23 07:21:25
非常感谢你! – 2012-02-23 16:20:28
你在你的控制器接收怎么办? – jgauffin 2012-02-23 06:54:36
我总是得到“q”的正确值,而“成分”则为null。 – 2012-02-23 06:56:06