0

I followed this tutorial to create a Restful web-api service. Everything seemed to work well, I can get all the bookings in JSON format by requesting them from the correct url. My issue is with the http POST.

My Javascript is:

var url = 'http://localhost:9077/api/bookings';
....
    var newEvent = [];

    newEvent.EventDateTime = // (now);
    newEvent.Name = "MyFirstBooking";

    function btnSubmit_Click()
    {
        alert("Submit clicked: " + newEvent.Name + "\n" + newEvent.EventDateTime);

        $.ajax({
            type: "POST",
            url: url,
            data: JSON.stringify( { Bookings: newEvent }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data) { alert(data); }
        });
    }

The alert displays the correct date and also the correct name. When I click Submit and check fiddler it looks like the JSON is correctly formatted:

 {"Bookings":[{"Name":"MyFirstBooking","EventDateTime":"2014-04-14T13:45:00.000Z"}]}

My View is Bookings.cs :

public class Bookings
{
    public int ID { get; set; }
    public string Name { get; set; }
    public DateTime BookingDateTime { get; set; }
    public DateTime EventDateTime { get; set; }
    public int Duration { get; set; }
    public int UserID { get; set; }
}

In my BookingsController I have:

    public HttpResponseMessage PostBooking(Bookings item)
    {
         // Implementation
    }

However when I put a breakpoint after PostBooking, item.EventDateTime is {01/01/0001 00:00:00} and Name is null. It seems like the JSON is not being deserialised correctly...? I'm not sure where this happens as I can't find it mentioned anywhere...

Thanks.

cdsln
  • 830
  • 1
  • 11
  • 33

2 Answers2

1

ahhh dates in javascript. Aren't they fun? You are more than likely going to have to do a converstion either in javascript or take a look at this stack overflow question to implement a custom date handler in your api:

ASP.NET Web API Date format in JSON does not serialise successfully

EDIT: Ahh i also noticed that your JSON object is an array. You will need to change your signature to take an array:

public HttpResponseMessage PostBooking(IEnumerable<Bookings> items)
{
     // Implementation
}

EDIT AGAIN:

on second thought, I dont think your event needs to be an array. I think you want to do this:

var newEvent ={};

this will intialize newEvent as an object instead of a an array. then you can leave your signature as is. You might need to change your param name like tomasofen mentioned in his answer as well.

EDIT AGAIN:

further thought: you dont need to root the object with {"Bookings": newEvent } just do this instead:

    $.ajax({
        type: "POST",
        url: url,
        data: JSON.stringify(newEvent),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) { alert(data); }
    });

you are setting the contentType to json. This tells your web app that the content should be json, which in turn will be handled and converted by the server. By stringifying it, you are turning the content into a string and therefore changing the contentType.

Community
  • 1
  • 1
kmacdonald
  • 3,381
  • 2
  • 18
  • 22
  • I removed the DateTime object and put in a reference to a 'UserID' property, so now there are no references to any DateTime obj in Javascript, and I am still getting `null` for the item. I changed `newEvent = {};` too. My new JSON string is `{"item":{"Name":"MyFirstBooking","UserID":2}}` – cdsln Apr 13 '14 at 23:52
  • did you try tomasofen's answer as well? I think he may also be correct. – kmacdonald Apr 13 '14 at 23:58
  • We don't know the definition for Bookings in the server side, but thinking on it, it is in plural and perhaps it is in fact some kind of collection. You can try to make a test changing the definition of item in the server function to simply an array of objects, to ckeck if something else is failing... – tomasofen Apr 14 '14 at 00:01
  • When I don't stringify nothing is passed in the JSON tab in Fiddler, however the data `Name=MyFirstBooking&UserID=2` is in the RAW tab. I've added the Bookings.cs class to my original question. Also when I don't stringify, `item` in PostBooking is null. When I do stringify, the object is created but all properties are null/default – cdsln Apr 14 '14 at 00:14
  • 1
    Yeah actually i just did some searching and you can stringify the object. I think the more important part is not to make a root property called bookings. just stringify the newEvent object. if you think about it you are passing an object with a book object inside of it to the server. The server is just expecting a booking object. – kmacdonald Apr 14 '14 at 00:16
  • Excellent, I changed it to `data: JSON.stringify(newEvent),` and it came through. Thanks. – cdsln Apr 14 '14 at 00:23
  • Whew! great! glad i could help. if you could please mark this as the answer. – kmacdonald Apr 14 '14 at 00:27
0

Try using the same name for the variable in the server method than the name of the Json parameter:

For server side:

public HttpResponseMessage PostBooking(Bookings item)
    {
         // Implementation
    }

For client side (just change "item" as name of the param):

{"item":[{"Name":"MyFirstBooking","EventDateTime":"2014-04-14T13:45:00.000Z"}]}

I had issues with this, and perhaps this is your case. Tell us if it works or not to try other things.

Check also that the object Bookings in the server has the members Name and EventDateTime writen in the same way.

tomasofen
  • 1,330
  • 2
  • 12
  • 16