开发者

FullCalendar isn't showing events

I'm using the arshaw's FullCalendar jQuery plugin on ASP.NET 4. Everything is okay, the events are fetched, but they're not displayed in the calendar. I'm sure they're fetched, FireBug shows the response like this:

{"d":[{"__type":"CalendarioEvento","title":"Samara Dos Santos 
Freitas","start":1304441400,"color":null},
{"__type":"CalendarioEvento","title":"Apae","start":1304443800,"color":null},
{"__type":"CalendarioEvento","title":"Apae","start":1304447400,"color":null},
{"__type":"CalendarioEvento","title":"Samara Dos Santos 
Freitas","start":1304449800,"color":null}]}

I also tried a events array manually serialization, but it doesn't work.

The $.ajax() in fullcalendar.js:

$.ajax($.extend({}, ajaxDefaults, source, {
                type: "POST",
                data: JSON.stringify(data),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(events) {
                    events = events || [];
                    var res = applyAll(success, this, arguments);
                    if ($.isArray(res)) {
                        events = res;
                    }
                    callback(events);
                },
                error: function() {
                    applyAll(error, this, arguments);
                    callback();
                },
                complete: function() {
                    applyAll(complete, this, arguments);
                    popLoading();
                }
            }));

Here's my VB code to fecth the events from the database and return them to the plugin:

Imports System.Web.Services
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration.ConfigurationManager
Imports Newtonsoft.Json

<System.Web.Script.Services.ScriptService()> _
Partial Class _Default
Inherits System.Web.UI.Page

Private Shared Function ToUnixTimespan(ByVal d As DateTime) As Long
    Dim time As New TimeSpan()
    time = d.ToUniversalTime().Subtract(New DateTime(1970, 1, 1, 0, 0, 0))

    Return CType(Math.Truncate(time.TotalSeconds), Int64)
End Function

Private Shared Function FromUnixTimespan(ByVal s As String) As DateTime
    Dim time As DateTime = New DateTime(1970, 1, 1, 0, 0, 0)
    Return time.AddSeconds(s)
End Function

<WebMethod()> _
Public Shared Function ListarEventos(ByVal starte As String, ByVal ende As String) As List(Of CalendarioEvento)
    Dim conexaoSql As New SqlConnection(ConnectionStrings("praeConnectionString").ConnectionString)
    Dim comandoSql As SqlCommand = New SqlCommand("spListarEventosCalendario", conexaoSql)
    comandoSql.CommandType = CommandType.StoredProcedure
    comandoSql.Parameters.AddWithValue("@bitPendentes", 0)
    comandoSql.Parameters.AddWithValue("@agendamentos", "188,135")
    comandoSql.Parameters.AddWithValue("@start", FromUnixTimespan(starte))
    comandoSql.Parameters.AddWithValue("@end", FromUnixTimespan(ende))
    comandoSql.Parameters.AddWithValue("@veiculo", "M01")
    Dim eventos As List(Of CalendarioEvento) = New List(Of CalendarioEvento)
    Try
        conexaoSql.Open()
        Dim sdrEventos As S开发者_运维技巧qlDataReader = comandoSql.ExecuteReader
        While sdrEventos.Read
            Dim evento As New CalendarioEvento
            evento.title = StrConv(sdrEventos("vchNome").ToString, VbStrConv.ProperCase)
            evento.start = ToUnixTimespan(Convert.ToDateTime(sdrEventos("vchData") + " " + sdrEventos("vchHora")))
            eventos.Add(evento)
        End While
    Catch ex As Exception

    Finally
        conexaoSql.Close()
    End Try
    comandoSql.Parameters("@bitPendentes").Value = 1
    Try
        conexaoSql.Open()
        Dim sdrEventos As SqlDataReader = comandoSql.ExecuteReader
        While sdrEventos.Read
            Dim evento As New CalendarioEvento
            evento.title = StrConv(sdrEventos("vchNome").ToString, VbStrConv.ProperCase)
            evento.start = ToUnixTimespan(Convert.ToDateTime(sdrEventos("vchData") + " " + sdrEventos("vchHora")))
            evento.color = "#6AB0D8"
            eventos.Add(evento)
        End While
    Catch ex As Exception

    Finally
        conexaoSql.Close()
    End Try
    Return eventos
End Function

End Class

Anyone have a solution?

Thanks a lot.


Here is the catch

instead of

events = events || [];

use

events = events.d || [];

with d parameter and it will work. If you want to know what is this freaking d, you should update your rss reader with Encosia blog. This d is introduced in ASP.NET 3.5 (It's not present in MVC, beacuse it's different framework).

Quote from his blog:

This is the case with all ASMX services JSON serialized through the ASP.NET AJAX Extensions in ASP.NET 3.5. Even if you’re only returning a scalar return value, such as a string, int, or boolean, the result will always be enclosed within the “d”. Why did it change? While I wish this unexpected change had been more clearly announced, it’s a good one. Here’s how Dave Reed explained it to me:

{"d": 1 }

Is not a valid JavaScript statement, where as this:

[1] Is.

So the wrapping of the "d" parameter prevents direct execution of the string as script. No Object or Array constructor worries.

[] is JavaScript’s array literal notation, allowing you to instantiate an array without explicitly calling a constructor. To expand on Dave’s explanation, simply consider this code: ["Dave", alert("Do Evil"), "Ward"] That literal array declaration will execute the alert in most browsers. Danger!

You could even do some workaround to make it work both with ASP.NET 2.0 and ASP.NET 3.5+

 if (events.hasOwnProperty('d')){
   events = events.d || [];
 }
 else {
   events = events || [];
 }

And since jquery version 1.5.1 you can use

$.ajaxSetup({
            converters: {
            // Evaluate text as a json expression
            "text json": function(data) {
            var res = $.parseJSON(data);
            return res.hasOwnProperty(‘d’) ? res.d : res;
}

so you don't even have to touch the fullcallendar.js code


I am not sure what "d" is and what _type is but this how it should look from the server

[{"id":17667,"title":"Daily - 30days","allDay":false,"start":"6/4/2011 1:00:00 PM","end":"6/4/2011 2:00:00 PM","color":"#C0F8F9","textColor":"#000000","isCustomProperty":true},
{"id":17669,"title":"Test","allDay":true,"start":"6/5/2011 12:00:00 AM","end":"6/5/2011 11:59:00 PM","color":"#C0F8F9","textColor":"#000000","isCustomProperty":true},
{"id":17677,"title":"Weekly - Month","allDay":false,"start":"6/1/2011 1:00:00 PM","end":"6/1/2011 2:00:00 PM","color":"#C0F8F9","textColor":"#000000","isCustomProperty":true}]

I think it's probably since you wrapped the stuff around with "d" first then "_type" full calendar probably can't extract it.


check out the following

How to use Jquery fullcalender in asp.net

EDIT

There is some issue in fullcalender plugin.Follow the steps provided in this link and modified the plug in code accordingly


@nemke: Your answer helped me with getting my code to work. Thank you! I did have to deserialize my result from the web service like this, though:

$.ajaxSetup({
    converters: {
        // Evaluate text as a json expression
        "text json": function (data) {
            var res = $.parseJSON(data);
            return res.hasOwnProperty('d') ? Sys.Serialization.JavaScriptSerializer.deserialize('(' + res.d + ')') : Sys.Serialization.JavaScriptSerializer.deserialize('(' + res + ')');
        }
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜