views:

248

answers:

1

Hi, I am currently trying to implement the wonderful jQuery plugin 'week calendar' (here) in my simple asp.net website. I have set up a couple of [WebMethods] to send data to the calendar and to respond to client side events (creating events, modifying events etc).

asp.net's automatic serialization of objects when using WebMethods seems to work well when sending the data back, but when the reverse is happening I'm running into issues.

The javascript code in question that sends the calendar event back to the server is as follows:

save: function() {
                    calEvent.id = id;
                    id++;
                    calEvent.start = new Date(startField.val());
                    calEvent.end = new Date(endField.val());
                    calEvent.title = titleField.val();
                    calEvent.body = bodyField.val();

                    $calendar.weekCalendar("removeUnsavedEvents");
                    $calendar.weekCalendar("updateEvent", calEvent);
                    $dialogContent.dialog("close");
                    //SAVE TO DATABASE

                    $.ajax({
                        type: "POST",
                        url: "Tracker.aspx/AddEvent",
                        data: calEvent,
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function(data) {
                            alert("saved");
                        }
                    });

Currently I just have a 'stub method' on the server to check that de-serialization works:

[WebMthod]    
public static string AddEvent(Event e)
        {
            //save event to database and return something
            return "done";
    }

However, I'm picking up the following exception when adding an event:

Invalid JSON primitive: start.

On the server, my event object is made up as follows:

[DataContract]
public class Event
{
    [DataMember]
    public int id { get; set; }
    [DataMember]
    public string title { get; set; }
    [DataMember]
    public string body { get; set; }
    [DataMember]
    public string start { get; set; }
    [DataMember]
    public string end { get; set; }
}
A: 

Modifying the call to the web service as follows did the trick:

$.ajax({
                        type: "POST",
                        url: "Tracker.aspx/AddEvent",
                        data: '{e : ' + JSON.stringify(calEvent) + '}',
                        contentType: "application/json; charset=utf-8",
                        dataType: "text",
                        success: function(data) {
                            alert("saved");
                        }
                    });

Just had to fiddle with the format of the JSON being sent to the server by using the JSON.stringify function

Sergio