使用ASP.NET,C#和JSON将事件添加到完整日历

时间:2015-10-28 10:45:21

标签: c# jquery asp.net json fullcalendar

好的,所以我知道这可能与这个问题有点重复:fullCalendar events not showing even though correct JSON feed 但在尝试了无效的代码后,我想我会发布另一个问题,看看是否有任何机构可以提供帮助

基本上我尝试使用来自SQL Server数据库的数据,使用ASP.NET C#动态地将事件添加到完整日历JQuery插件中。

以下是我在代码隐藏文件

中的Web方法中使用的代码
[WebMethod]
public static String TestOnWebService()
{

    String connectionString = WebConfigurationManager.ConnectionStrings["UniString"].ConnectionString;
    SqlConnection myConnection = new SqlConnection(connectionString);

    myConnection.Open();

    String query = "SELECT * FROM timetable";

    SqlCommand cmd = new SqlCommand(query, myConnection);

    SqlDataReader reader = cmd.ExecuteReader();


    string myJsonString = "";
    List<object> myList = new List<object>();


    if (reader.HasRows)
    {
        var indexOfId = reader.GetOrdinal("id");
        var indexOfLecture = reader.GetOrdinal("lecture");
        var indexOfStartDate = reader.GetOrdinal("start_date");
        var indexOfEndDate = reader.GetOrdinal("end_date");
        var indexOfTimeStart = reader.GetOrdinal("start_time");
        var indexOfTimeEnd = reader.GetOrdinal("end_time");


        while (reader.Read())
        {

            var Id = reader.GetValue(indexOfId).ToString();
            var Lecture = reader.GetValue(indexOfLecture).ToString();
            var DateStart = reader.GetValue(indexOfStartDate).ToString();
            var DateEnd = reader.GetValue(indexOfEndDate).ToString();
            var StartTime = reader.GetValue(indexOfTimeStart);
            var EndTime = reader.GetValue(indexOfTimeEnd);


            //Convert Implicity typed var to Date Time
            DateTime RealStartDate = Convert.ToDateTime(DateStart);
            DateTime RealEndDate = Convert.ToDateTime(DateEnd);


            //Convert Date Time to ISO
            String SendStartDate = RealStartDate.ToString("s");
            String SendEndDate = RealEndDate.ToString("s");


            timeTable t_table = new timeTable(Id, Lecture, SendStartDate, SendEndDate);


            myList.Add(t_table);


        }
        myJsonString = (new JavaScriptSerializer()).Serialize(myList);


        myConnection.Close();
    }

    return myJsonString;

}

}

这是我用来通过POST方法获取JSON数据的AJAX调用:

$(document).ready(function () {

$('#calendar').fullCalendar({
    header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay'
    },
    eventClick: function() {
        alert('a day has been clicked!');
    }, 
    events: function (start, end, callback) {
        $.ajax({
            type: "POST",    
            url: "webserv.aspx/TestOnWebService",   
            contentType: "application/json; charset=utf-8",  
            dataType: "json",
            success: function (doc) {
                alert("Success");
                var events = [];
                alert(doc.d);
                var obj = $.parseJSON(doc.d);  
                console.log(obj);
                $(obj.event).each(function () {                           
                    events.push({
                        title: $(this).attr('title'),  
                        start: $(this).attr('start'),     
                        end: $(this).attr('end'),
                        id: $(this).attr('id')
                    });
                });                     
                //callback(events);
                callback && callback(events);
            },
            error: function(xhr, status, error) {
                alert(xhr.responseText);
            }
        });
    }
})

})

AJAX调用似乎成功,因为我可以提醒成功消息,我也可以提醒JSON数据,如下所示:

alert(doc.d)

我还可以在控制台中输出JSON数据的解析对象,如下所示:

var obj = $.parseJSON(doc.d);

我执行此操作时控制台中没有出现任何错误,但事件似乎没有添加到完整日历用户界面(在我的页面上也显示正常)。

我想我可能会在以下代码的某个地方出错,但我似乎无法指责它:

$(obj.event).each(function () {                           
  events.push({
  title: $(this).attr('title'),  
  start: $(this).attr('start'),     
  end: $(this).attr('end'),
  id: $(this).attr('id')
});

我也得到一个错误&#34;回调不是一个功能&#34;当我使用这段代码时:

callback(events);

但是当我使用它时不是:

callback && callback(events);

我不确定这是否与我遇到的问题有关,但我想我会将其添加以防万一。

提前感谢您的任何回复,我们非常感谢。

编辑:

道歉,我忘了为我的timeTable类添加代码。它如下:

public class timeTable
{
public String id { get; set; }
public String title { get; set; }
public String start { get; set; }
public String end { get; set; }

public timeTable(String I, String t, String ds, String de)
{
    this.id = I;
    this.title = t;
    this.start = ds;
    this.end = de;
}


}

我的HTML实际上只是一行:

<div id="calendar"></div> 

以下是我在页面头部链接的javascript文件

        <!-- Javascript -->
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src='js/moment.js'></script>
<script src='js/fullcalendar.js'></script>
<script src="js/script.js"></script>

更新

我尝试过的另一件事是使用我的JSON字符串循环遍历我创建的对象并将其推入事件数组中,但这似乎也不起作用。请参阅以下代码:

$(document).ready(function () {

$('#calendar').fullCalendar({
    header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay'
    },
    eventClick: function () {
        alert('a day has been clicked!');
    },
    events: function (start, end, callback) {
        $.ajax({
            type: "POST",
            url: "webserv.aspx/TestOnWebService",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (doc) {
                alert("Success");
                var events = [];
                alert(doc.d);
                var obj = $.parseJSON(doc.d);
                console.log(obj);

                for (var k in obj) {// k represents the id keys 1,2,3
                    var d = obj[k]; // We assign a the reference to each id object to the d variable
                      for (var p in d) { //Next we access the nested objects by using the p variable
                          if (p.hasOwnProperty) { //Check to make sure p has its own properties
                              //alert(p + ":" + d[p]); //We alert the key (d) and the keys value (d[p])
                              events.push(p + ": " + d[p]);
                              }

                            }
                     }
                console.log(events);

            },
            error: function (xhr, status, error) {
                alert(xhr.responseText);
            }
        });
    }
})

})

它将数组输出到控制台,但仍未在完整日历用户界面上显示任何事件: - (

更新2

这是我的下一个代码编辑,它似乎也没有用,我不确定为什么因为它使用所需的值填充事件数组,我还添加了addDay =&#34; false& #34;属性也是如此,但仍然没有快乐,任何身体都有任何想法,我很难过:

$(document).ready(function () {

$('#calendar').fullCalendar({
    header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay'
    },
    eventClick: function () {
        alert('a day has been clicked!');
    },
    events: function () {
        $.ajax({
            type: "POST",
            url: "webserv.aspx/TestOnWebService",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (doc) {
                alert("Success");
                var events = [];
                //console.log(doc.d);
                var obj = $.parseJSON(doc.d);
                //console.log(obj);

                $.each(obj, function (index) {

                    $.each(obj[index], function (key, value) {

                        events.push(key + ": " + value)


                    });

                });

                console.log(events);

            },
            error: function (xhr, status, error) {
                alert(xhr.responseText);
            }
        });
    }
})

})

4 个答案:

答案 0 :(得分:2)

更正确:

<script>

    $(document).ready(function () {

        $.ajax({
            type: "POST",
            url: "../04_Entries/04_42_ReservationCalander.aspx/TestOnWebService",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (doc) {

                var events = [];
                var docd = doc.d;


                var obj = $.parseJSON(doc.d);
                console.log(obj);


               $('#calendar').fullCalendar({
                    header: {
                        left: 'prev,next today',
                        center: 'title',
                        right: 'month,agendaWeek,agendaDay'
                    },
                    eventClick: function () {

                    },

                    editable: false,

                    events: obj //Just pass obj to events
                })
                console.log(events);

            },
            error: function (xhr, status, error) {
                alert(xhr.responseText);
            }
        });
    });

</script>

答案 1 :(得分:1)

I solved this by adding parameter in the 'events: function ()', to 'events: function (start, end,timezone, callback). It should work now.

答案 2 :(得分:0)

在您的原始代码中,我相信您正确定义了“每个”功能。删除'obj中的'事件。并使用'回调(事件)。这应该是:

//only use 'obj' which has the list of events
    $(obj).each(function () {                           
       events.push({
       title: $(this).attr('title'),  
       start: $(this).attr('start'),     
       end: $(this).attr('end'),
       id: $(this).attr('id')
       });
    });                     
    callback(events);
    //callback && callback(events);

答案 3 :(得分:0)

这对我有用

create proc testfunc( @input varchar(50))
as 
begin

    select * into #temp from ufnGetTVP(@input)

    select * from #temp

    IF OBJECT_ID('tempdb..#temp') IS NOT NULL drop table #temp

end