1

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

1 Answer 1

1

Try the following:

  1. Specifically set the "contentType" on your jQuery AJAX call to JSON. jQuery submits as 'application/x-www-form-urlencoded; charset=UTF-8' by default.
  2. JSON.stringify your array

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));
});
1
  • That seemed to do the trick...wow. How random. Thanks so much!
    – David
    Nov 13, 2014 at 15:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.