【问题标题】:Events won't render to Fullcalendar from C#事件不会从 C# 呈现到 Fullcalendar
【发布时间】:2017-06-16 12:03:15
【问题描述】:

我正在准备好文档中创建 fulcalendar,并且我有一个运行以下 C# 函数来获取数据的 asp 按钮。

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

   }

我正在创建完整的日历,准备好文档,

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

    });

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

var event=[{ id:1, title:"manoj", start:"2017-06-15T22:30:00.000Z", 结束:“2017-06-15T23:30:00.000Z”}];

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

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

谁能告诉我为什么事件没有呈现?我已经在这里工作了好几个小时了。

更新 我将 C# 更改为 web 方法,

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

回调在运行时变为“假”,但我可以看到网络方法在格式化日期后在警报中返回它,

我正在从 aspx 中获取数据,我可以在 jquery 中读取它,但我仍然无法渲染一个 even。此时我不知道该怎么做 eles。你能看看我的代码并指出什么问题吗?我也不明白函数中 (start,end,callback) 的使用,因为我在 webmethod 中也不使用它。

【问题讨论】:

  • 你的loadCal(eventList)函数是在click上调用的吗?
  • loadCal 最有可能在 fullCalendar 创建日历对象之前调用。您需要稍微重组您的 js 以确保正确的顺序

标签: c# jquery asp.net json fullcalendar


【解决方案1】:

我终于解决了我的问题。

我的 C# 获取数据并作为 JSON 传递的方法是,

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

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

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

【讨论】:

    【解决方案2】:
    [{ 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/

    注意如果您不能完全让您的服务器方法符合直接 JSON 提要的要求,您可以使用 JavaScript 函数作为中介来更改参数的格式和/或在传递之前更改返回数据的格式到完整日历。见https://fullcalendar.io/docs/event_data/events_function/

    如果您实施其中一种解决方案,管理日历上的事件会容易得多。

    【讨论】:

    • 我现在将我的函数更改为 web 方法。我只是无法让它继续工作。你能看看更新吗?非常感谢!
    • 嘿,我修好了。非常感谢您的帮助。
    • @PeeBee 没问题,很高兴您能够修复它。如果答案对您有所帮助,请考虑投票和/或将其标记为已接受的答案,谢谢:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多