事件不会从C#渲染到Fullcalendar

时间:2017-06-16 12:03:15

标签: c# jquery asp.net json fullcalendar

我在文档就绪中创建了fulcalendar,我有一个asp按钮,它运行以下C#函数来获取数据。

 public void getAppointments()
    {
        List<Appoinment> appoinmentList = new List<Appoinment>();
        AppointmentController appointmentController = new AppointmentController();
        PublicUserProfileController publicUserProfileController = new PublicUserProfileController();
        PublicUserProfile publicUserProfile = new PublicUserProfile();
        //appoinmentList = appointmentController.fetchAppointmentByConsultent(Int32.Parse(Session["ICid"].ToString()));
        appoinmentList = appointmentController.fetchAppointmentByConsultent(3);

        var frontAppoinmentList = new List<object>();

        foreach (var appoinment in appoinmentList)
        {
            publicUserProfile = publicUserProfileController.fetchPublicUserNameById(appoinment.PublicUserProfileId);
            var name = publicUserProfile.FirstName + " " + publicUserProfile.LastName;

            frontAppoinmentList.Add(new
            {
                id = appoinment.Id.ToString(),
                title = name,
                start = appoinment.UtcStartTime,
                end = appoinment.UtcEndTime
            });

        }

        // Serialize to JSON string.
        JavaScriptSerializer jss = new JavaScriptSerializer();
        String json = jss.Serialize(frontAppoinmentList);
        var msg = String.Format("<script>loadCal('{0}');</script>", json);

        //ClientScript.RegisterStartupScript(GetType(), "hwa", msg, true);
        ScriptManager.RegisterClientScriptBlock(this, GetType(), "none", msg, false);

    }

    protected void btnmonthly_Click(object sender, EventArgs e)
    {
        getAppointments();
    }

我让我的JS捕获JSON并将事件加载为

function loadCal(eventList){
    eventList = $.parseJSON(eventList);
    alert(JSON.stringify(eventList));

        for (var j = 0; j < eventList.length; j++) {

        eventList[j].start = new Date(parseInt(eventList[j].start.replace("/Date(", "").replace(")/",""), 10));
        eventList[j].end = new Date(parseInt(eventList[j].end.replace("/Date(", "").replace(")/",""), 10));


    };
    alert(JSON.stringify(eventList[0].start));

        for (var j = 0; j < eventList.length; j++) {
            var eId = eventList[0].id;
            var eStart = eventList[0].start.toISOString();
            var eEnd = eventList[0].end.toISOString();
            var eTitle = eventList[0].title;
                    var event=
                    [{
                        id: eId,
                        title: eTitle,
                        start: eStart ,
                        end:eEnd

                    }];

                    $('#appCalendar').fullCalendar( 'renderEvent', event, true);
                };

   }

我在文档就绪中创建了fullcalendar,

$('#appCalendar').fullCalendar({
        header: {
            left: 'prev,next today',
            center: 'title',
            right: ''
        },
        defaultDate: today,
        defaultView: 'month',
        editable: true

    });

渲染事件不会渲染任何事件,但如果我在控制台中传递它,则会渲染事件。

  

var event = [{id:1,title:&#34; manoj&#34 ;, start:&#34; 2017-06-15T22:30:00.000Z&#34;,   端:&#34; 2017-06-15T23:30:00.000Z&#34; }];

     

$(&#39;#appCalendar&#39;)。fullCalendar(&#39; renderEvent&#39;,event,true);

这正是我对loadCal函数的期望与我传递的json有关。这些是我在loadCal中检查断点时为事件数组(eTitle,eId等)设置的值。

有人可以告诉我为什么事件没有呈现?我已经在这几个小时了。

更新 我将C#更改为webmethod,

[WebMethod(EnableSession = true)]
    public static string GetEvents()
    {
        List<Appoinment> appoinmentList = new List<Appoinment>();
        AppointmentController appointmentController = new AppointmentController();
        PublicUserProfileController publicUserProfileController = new PublicUserProfileController();
        PublicUserProfile publicUserProfile = new PublicUserProfile();
        //appoinmentList = appointmentController.fetchAppointmentByConsultent(Int32.Parse(Session["ICid"].ToString()));
        appoinmentList = appointmentController.fetchAppointmentByConsultent(3);

        var frontAppoinmentList = new List<object>();

        foreach (var appoinment in appoinmentList)
        {
            publicUserProfile = publicUserProfileController.fetchPublicUserNameById(appoinment.PublicUserProfileId);
            var name = publicUserProfile.FirstName + " " + publicUserProfile.LastName;

            frontAppoinmentList.Add(new
            {
                id = appoinment.Id.ToString(),
                title = name,
                start = appoinment.UtcStartTime,
                end = appoinment.UtcEndTime
            });

        }

        // Serialize to JSON string.
        JavaScriptSerializer jss = new JavaScriptSerializer();
        String json = jss.Serialize(frontAppoinmentList);
        return json;
    }

和我的Jquery,

$(document).ready(function () {
    $('#appCalendar').fullCalendar({
    eventClick: function() {
        alert('a day has been clicked!');
    }, 
        events: function (start, end, callback) {
        $.ajax({
            type: "POST",    //WebMethods will not allow GET
            url: "AppointmentDiary.aspx/GetEvents",   //url of a webmethod - example below

            //completely take out 'data:' line if you don't want to pass to webmethod - Important to also change webmethod to not accept any parameters 
            contentType: "application/json; charset=utf-8",  
            dataType: "json",
            success: function (doc) {
                var events = [];   //javascript event object created here
                var obj = $.parseJSON(doc.d);  //.net returns json wrapped in "d"
                $(obj).each(function () {
                        var startd=     new Date(parseInt(this.start.replace("/Date(", "").replace(")/",""), 10));
                        var endd = new Date(parseInt(this.end.replace("/Date(", "").replace(")/",""), 10));                 
                        events.push({
                        title: this.title,  //your calevent object has identical parameters 'title', 'start', ect, so this will work
                        start:startd.toISOString(), // will be parsed into DateTime object    
                        end: endd.toISOString(),
                        id: this.id
                    });
                });                     
                //if(callback) callback(events);
                //$('#appCalendar').fullCalendar( 'renderEvent',events[0], true);
                alert(JSON.stringify(events[0]));

            }
        });
        return events;
    }
   });
});

回拨变为“假”&#39;当它运行但我可以看到webmethod格式化日期后在警报中返回此内容,

enter image description here

我从aspx获取数据,我可以在jquery中读取它,但我仍然无法呈现even.at这一点我不知道要做什么。你可以看看我的代码,并指出什么是错的?我也不理解函数的使用(开始,结束,回调),因为我还没有在web方法中使用它。

2 个答案:

答案 0 :(得分:1)

我终于解决了我的问题。

用于获取数据和作为JSON传递的我的C#方法是

[WebMethod(EnableSession = true)]
    public static string GetEvents()
    {
        List<Appoinment> appoinmentList = new List<Appoinment>();
        AppointmentController appointmentController = new AppointmentController();
        PublicUserProfileController publicUserProfileController = new PublicUserProfileController();
        PublicUserProfile publicUserProfile = new PublicUserProfile();
        //appoinmentList = appointmentController.fetchAppointmentByConsultent(Int32.Parse(Session["ICid"].ToString()));
        appoinmentList = appointmentController.fetchAppointmentByConsultent(3);

        var frontAppoinmentList = new List<object>();

        foreach (var appoinment in appoinmentList)
        {
            publicUserProfile = publicUserProfileController.fetchPublicUserNameById(appoinment.PublicUserProfileId);
            var name = publicUserProfile.FirstName + " " + publicUserProfile.LastName;

            frontAppoinmentList.Add(new
            {
                id = appoinment.Id.ToString(),
                title = name,
                start = appoinment.UtcStartTime,
                end = appoinment.UtcEndTime
            });

        }

        // Serialize to JSON string.
        JavaScriptSerializer jss = new JavaScriptSerializer();
        String json = jss.Serialize(frontAppoinmentList);
        return json;
    }

我的Jquery用于创建Fullcalendar并呈现事件,

 $(document).ready(function () {

    $.ajax({
        type: "POST",
        url: "AppointmentDiary.aspx/GetEvents",
        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);
            alert(JSON.stringify(obj));
for (var j = 0; j < obj.length; j++) {

        obj[j].start = new Date(parseInt(obj[j].start.replace("/Date(", "").replace(")/",""), 10));
        obj[j].start = obj[j].start.toISOString();
        obj[j].end = new Date(parseInt(obj[j].end.replace("/Date(", "").replace(")/",""), 10));
        obj[j].end = obj[j].end.toISOString();


    };

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

答案 1 :(得分:0)

[{ id:1, title:"manoj", start:"2017-06-15T22:30:00.000Z", end:"2017-06-15T23:30:00.000Z" }] 

数组renderEvent方法需要对象。尝试发送

{ id:1, title:"manoj", start:"2017-06-15T22:30:00.000Z", end:"2017-06-15T23:30:00.000Z" }

代替。

或者,使用renderEvents(注意复数)方法(https://fullcalendar.io/docs/event_rendering/renderEvents/)并调用一次,将其eventList作为参数发送(您必须整理一下)正如你现在所做的那样,每个事件中的日期都是第一个,尽管你可以在服务器上实际执行此操作而不是更高效。使用JSON.NET作为序列化程序可以解决它。)

但是......实际上,这并不是您打算如何使用fullCalendar加载大量事件列表。在客户端完成所有操作都会很慢,而且您正在将所有事件一次性加载到其中 - 想象一下当您的应用程序运行一段时间并且您有一整年的时间值得或更多,它会更慢,也许没有人会看到旧的。

相反,您应该创建一个单独的服务器方法(例如WebMethod或其他JSON服务),它可以接受开始和结束日期,并且只返回这些日期之间的相关事件。当你启动它时,你告诉fullCalendar这个方法的URL,如下所示:

events: "Events.aspx/GetEvents"

然后,当日历开始时,它从服务器(通过AJAX)请求仅针对当时日历上实际显示的日期的事件。当日期或视图发生更改时,它会请求新日期的更新列表。最重要的是,它会自动完成,无需您进一步干预。有关此方法的详细信息,请参阅https://fullcalendar.io/docs/event_data/events_json_feed/

N.B。如果您无法使服务器方法符合直接JSON提要的要求,则可以使用JavaScript函数作为中介来更改参数的格式和/或在传递之前更改返回数据的格式到fullCalendar。见https://fullcalendar.io/docs/event_data/events_function/

如果您实施其中一种解决方案,则可以更轻松地管理日历上的活动。