In ASP.NET MVC 3 I am not having any luck trying to send JSON data to my controller.
I loop through a list and generate JSON objects from the elements and then send them off along with my query parameter:
$.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
}
});
At the controller I have
[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);
}
Where JSONingredient is
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;
}
}
Which I made up because I thought my normal model which has additional properties which are not in the JSON was causing the problem, but I would have thought that if it did work it would have worked with my normal model...
I'm thinking that maybe the format in which I am sending the data is not correct. Examining the request in firefox show:
Parametersapplication/x-www-form-urlencoded ingredients[0][ID] 4 ingredients[0][Name] Water q sug
Source
q=sug&ingredients%5B0%5D%5BName%5D=Water&ingredients%5B0%5D%5BID%5D=4
Any help would be much appreciated.