使用ajax将json / javascript数据/对象传递给c#函数

时间:2014-04-10 14:07:53

标签: javascript ajax json webmethod

我正在使用FullCalendar(http://arshaw.com/fullcalendar/),我需要帮助将使用json的数据传递到我的ASP.net页面的代码隐藏页面中的c#函数。

我正在使用json在我的FullCalendar Web应用程序中加载数据:

代码背后:

    [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页面:

     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');
                    }
                });
             },

这很好用。现在我想通过调用函数并传递数据来保存数据。以下是我到目前为止所做的事情:

代码背后:

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

        return true;
    }

asp.x页面

    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;            
    }

上面的ajax帖子是我需要帮助的地方。变量事件包含所有FullCalendar事件信息。 如何传递数据&#39;事件&#39;功能&#39; SaveEvents&#39;? 如果需要,我可以更改SaveEvents签名。

EDIT 如果我改变我的c#函数来使用像s0这样的数组:

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

        return true;
    }

并通过以下数据传递:

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

然后使用大小为4的数组调用&#39; SaveEvents&#39; 函数,但所有数据值都为null,为什么会这样?

由于

1 个答案:

答案 0 :(得分:1)

从您的代码中可以看出,您将c#类作为

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;}
}

所以拿json数组。这是一个样本 //将作为数据提供给c#方法的数组

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"
  }
];

现在是将JSON对象传递给发布的URL的ajax请求

    $.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');
        }
    });

更新:

要确保没有其他错误,请将您的保存活动测试为。如果它正常,上面应该也可以,因为它适合我:)

[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');
        }
    });