Reputation: 2223
Alrighty, so here is where I am at.
I have some code that sends an array of goodies to a .NET WebAPI (c#).
var questions = [];
$('#questions').find('input').each(function(){
var text = $(this).val();
questions.push({ ID: 123, Question: text });
});
$.ajax({
type: 'POST',
url: _apiPath + '/main/savequestions',
data: { "" : questions }
}).done(function(data){
alert(JSON.stringify(data));
});
So I learned on a while back that .NET Web API gets confused with arrays and there is a known bug which is why you have to send the data with "" as the property name.
Here is my web api controller:
[Route("main/savequestions")]
[HttpPost]
public List<Question> SaveQuestions(List<Question> questions)
{
using (var mc = new MyContext())
{
List<Question> list = new List<Question>();
if (questions != null)
{
foreach (var item in questions)
{
var dbQ = new Question();
dbQ.ID = Guid.NewGuid();
dbQ.ToolID = item.ID;
dbQ.Question = item.Question;
mc.Questions.Add(dbQ);
list.Add(dbQ);
}
}
mc.SaveChanges();
return list;
}
}
This works fine when we are on a desktop. Everything saves...works...awesome.
So we are using PhoneGap and when we use the phonegap app to emulate the app running this code will not save any data. We have checked and made sure that the JSON we are sending is the same...but when we run it the controller seems to be getting an empty array and so it isn't saving anything.
The inconsistency is enough to drive me batty.
Help!
David
Upvotes: 1
Views: 169
Reputation: 252
Try the following:
This will tell WebAPI to use the JSON MediaTypeFormatter during the model binding: http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
I'm not sure why the discrepancy between the desktop and mobile browser unless the desktop browser or jQuery is treating the "data" differently.
$.ajax({
type: 'POST',
url: _apiPath + '/main/savequestions',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(questions)
}).done(function(data){
alert(JSON.stringify(data));
});
Upvotes: 1