FullCalendar插件不会在日历上呈现事件

时间:2018-03-07 08:49:34

标签: asp.net json web-services fullcalendar

我使用fullCalendar插件来显示ASP.NET ASMX Web服务中的事件。 JSON数据被正确获取并在控制台中显示正常。但事件不会在日历视图中呈现。我错过了什么?

$('#divcalendar').fullCalendar({
  defaultDate: '2018-03-12',
  editable: true,
  eventLimit: true, // allow "more" link when too many events
  events: function (start, end, timezone,callback) {

      $.ajax({
          type: "POST",
          url: 'Webservice.asmx/ListEvents',
          cache: false,
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          success: function (data) {
              var event = [];
              $(data.d).each(function () {
                  event.push({
                      title: this.Title,
                      start: this.Start,
                      end: this.End
                  });
              });
              console.log(event);
              callback(event);
          },
          error: function (jqXHR, textStatus, errorThrown) {
              alert('There was an error');
          }
      });
  }

});


[WebMethod]
public CalendarEvent[] ListEvents()
{
    DateTime epoc = new DateTime(1970, 1, 1);
    return new CalendarEvent[]
    {
    new CalendarEvent { Title = "Event 1", Start = new DateTime(2018,3,9,16,0,0).Subtract(epoc).TotalSeconds, End = new DateTime(2018,3,9,17,0,0).Subtract(epoc).TotalSeconds},
    new CalendarEvent { Title = "Event 2", Start = new DateTime(2018,3,12,12,0,0).Subtract(epoc).TotalSeconds, End = new DateTime(2018,3,12,13,0,0).Subtract(epoc).TotalSeconds}
    };
}

来自webservice的控制台输出

{"d":[{"__type":"CalendarEvent","End":1520614800,"Start":1520611200,"Title":"Event 1"},{"__type":"CalendarEvent","End":1520859600,"Start":1520856000,"Title":"Event 2"}]}

1 个答案:

答案 0 :(得分:1)

我认为你的日期被输入日历,但不是在你想要的地方。

虽然您没有明确提及,但我强烈怀疑您为开始日期和结束日期输出的时间戳是以秒为单位指定的。

现在,fullCalendar使用momentJS来解析提供给它的任何日期字符串或时间戳。或者,它可以接受现成的momentJS或JS Date对象。

momentJS可以通过momentJS构造函数自动解析时间戳(fullCalendar在收到你的时间戳值时会调用它),但它假定值以毫秒给出,而不是秒。

因此,当您提供1520611200(第一个事件的开始日期)时,它会以毫秒为单位解释,结果日期为1970-01-18 14:23:31

如果要以秒为单位指定日期,则必须使用moment.unix()方法。使用此方法,您的时间戳将被解释为2018-03-09 16:00:00,我认为这是您的意图。

请参阅http://jsfiddle.net/Loccoxds/1/获取演示,了解momentJS如何解析您的某个值。

要使代码正常工作,最简单的方法是:

success: function (data) {
      var event = [];
      $(data.d).each(function () {
          event.push({
              title: this.Title,
              start: moment.unix(this.Start),
              end: moment.unix(this.End)
          });
      });
      console.log(event);
      callback(event);
  },

这样,您就可以为fullCalendar提供现成的momentJS对象,并正确解析了时间戳。

有关在momentJS中解析时间戳的更多详细信息,请参阅http://momentjs.com/docs/#/parsing/unix-timestamp-milliseconds/

P.S。或者,当然您可以更改asmx服务,以momentJS可以自动解析的格式输出日期,例如以毫秒为单位的时间戳或ISO8601格式的日期字符串 - 有关详细信息,请参阅http://momentjs.com/docs/#/parsing/string/

P.P.S。 ASMX现在几乎是.NET中的遗留技术。您应该考虑使用WCF或Web API。 Microsoft建议不要使用ASMX创建新代码。