Harry Boy
Harry Boy

Reputation: 4777

Pass json/javascript data/objects to c# function using ajax

I'm using FullCalendar (http://arshaw.com/fullcalendar/) and I need help with passing data using json to a c# function in the code behind page of my ASP.net page.

I am using json to load data like so in my FullCalendar web application:

Code behind:

    [WebMethod]
    public static List<Event> GetEvents()
    {
        List<Event> events = new List<Event>();
        events.Add(new Event()
        {
            EventID = 1,
            EventName = "EventName 1",
            StartDate = DateTime.Now.ToString("MM-dd-yyyy"),
            EndDate = DateTime.Now.AddDays(2).ToString("MM-dd-yyyy"),
            EventColor = "red"
        });
        events.Add(new Event()
        {
            EventID = 2,
            EventName = "EventName 2",
            StartDate = DateTime.Now.AddDays(4).ToString("MM-dd-yyyy"),
            EndDate = DateTime.Now.AddDays(5).ToString("MM-dd-yyyy"),
            EventColor = "green"
        });

        return events;
    }

asp.x page:

     events: function(start, end, callback)
            {
                $.ajax(
                {
                    type: 'POST',
                    contentType: 'application/json',
                    data: "{}",
                    dataType: 'json',
                    url: "Calendar.aspx/GetEvents",
                    cache: false,
                    success: function (response) {

                        var events = $.map(response.d, function (item, i) {
                            var event   = new Object();
                            event.id    = item.EventID;
                            event.start = new Date(item.StartDate);
                            event.end   = new Date(item.EndDate);
                            event.title = item.EventName;
                            event.color = item.EventColor;
                            return event;
                         })
                         callback(events);
                    },

                    error: function (err) {
                       alert('Error');
                    }
                });
             },

This is working fine. Now I want to save data by calling a function and passing it data. Here is what I have done so far:

Code behind:

    [WebMethod]
    public static bool SaveEvents(List<Event> events)
    {
        //iterate through the events and save to database

        return true;
    }

asp.x page

    function save() {
        var eventsFromCalendar = $('#calendar').fullCalendar('clientEvents');

        var events = $.map(eventsFromCalendar, function (item, i) {
            var event   = new Object();
            event.id    = item.id;
            event.start = item.start;
            event.end   = item.end;
            event.title = item.title;
            event.color = item.color;
            return event;
        });

        $.ajax(
        {
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(events),     **<-- I have to pass data here but how???**
            dataType: 'json',
            url: "Calendar.aspx/SaveEvents",
            cache: false,
            success: function (response) {
                alert('Events saved successfully');
            },

            error: function (err) {
                alert('Error Saving Events');
            }
        });
        return false;            
    }

The above ajax post is where I need help with. The variable events contais all the FullCalendar event info. How do I pass the data 'events' to the function 'SaveEvents'? I can change the SaveEvents signature if need be.

EDIT If I change my c# function to use an array like s0:

    [WebMethod]
    public static bool SaveEvents(Event[] newEvents)
    {

        return true;
    }

And pass the following data through:

    data: JSON.stringify({ newEvents: events }),

Then the function 'SaveEvents' gets called with an array of size 4 but all the data values are null, why is this?

Thanks

Upvotes: 1

Views: 6698

Answers (1)

Sami
Sami

Reputation: 8419

Obvious from your code that you have a c# class as

public class Events
{
    public int EventID {get; set;}
    public string EventName {get;set;}
    public StartDate {get; set;} 
    public string end {get; set;} 
    public string color {get; set;}
}

So take json array. A sample here // Array which would be provided to c# method as data

var newEvents=[     
  {
        EventID : 1,
        EventName : "EventName 1",
        StartDate : "2015-01-01",
        EndDate : "2015-01-03",
        EventColor : "red"
  },
  {
        EventID : 2,
        EventName : "EventName 2",
        StartDate : "2015-01-02",
        EndDate : "2015-01-04",
        EventColor : "green"
  }
];

Now the ajax request which passes JSON objects to posted URL

    $.ajax
    ({
        type: 'POST',
        contentType: 'json',
        data: {newEvents:newEvents},// Pass data as it is. Do not stringyfy
        dataType: 'json',
        url: "Calendar.aspx/SaveEvents"
        success: function (response) {
            alert('Events saved successfully');
        },
        error: function (err) {
            alert('Error Saving Events');
        }
    });

Update :

To make sure that there is nothing else wrong please test your Save Events as. If it goes fine above should work as well, As it is working for me :)

[WebMethod]
public static bool SaveEvents(string EventName)
{
    //iterate through the events and save to database

    return true;
}

    $.ajax
    ({
        type: 'POST',
        contentType: 'json',
        data: {EventName:'myevet 1'},
        url: "Calendar.aspx/SaveEvents",
        cache: false,
        success: function (response) {
            alert('Events saved successfully');
        },
        error: function (err) {
            alert('Error Saving Events');
        }
    });

Upvotes: 1

Related Questions