【问题标题】:Populating FullCalendar events from MVC从 MVC 填充 FullCalendar 事件
【发布时间】:2010-03-18 10:06:03
【问题描述】:

我在从 MVC 填充 FullCalendar 时遇到了困难,请在这件事上提供一些帮助。

我的控制器有以下代码:

    Function GetEvents(ByVal [start] As Double, ByVal [end] As Double) As JsonResult
    Dim sqlConnection As New SqlClient.SqlConnection

    sqlConnection.ConnectionString = My.Settings.sqlConnection

    Dim sqlCommand As New SqlClient.SqlCommand
    sqlCommand.CommandText = "SELECT tripID AS ID, tripName AS Title, DATEDIFF(s, '1970-01-01 00:00:00', dateStart) AS [Start], DATEDIFF(s, '1970-01-01 00:00:00', dateEnd) AS [End] FROM tblTrip WHERE userID=18 AND DateStart IS NOT NULL"
    sqlCommand.Connection = sqlConnection

    Dim ds As New DataSet
    Dim da As New SqlClient.SqlDataAdapter(sqlCommand)
    da.Fill(ds, "Meetings")
    sqlConnection.Close()

    Dim meetings = From c In ds.Tables("Meetings") Select {c.Item("ID"), c.Item("Title"), "False", c.Item("Start"), c.Item("End")}

    Return Json(meetings.ToArray(), JsonRequestBehavior.AllowGet)

End Function

这确实运行正确,但返回的格式是:

[[25,"南美 2008","假",1203033600,1227657600],[48,"黎凡特 2009","假",1231804800,1233619200],[49,"南美 2009","假",1235433600,1237420800],[50,"意大利 2009","假",1241049600,1256083200],[189,"黎凡特 2010a","假",1265414400,1267574400],[195,"黎凡特 2010a","假",1262736000,1262736000],[208,"黎凡特 2010a","假",1264982400,1267574400],[209,"黎凡特 2010a","假",1264982400,1265587200],[210,"黎凡特 2010", "假",1264982400,1266969600],[211,"黎凡特 2010 b","假",1267056000,1267574400],[213,"南美 2010a","假",1268438400,1269648000],[214,"黎凡特2010 c","假",1266364800,1264118400],[215,"南美 2010a","假",1268611200,1269648000],[217,"南美 2010","假",1268611200,1269561600],[ 218,"South America 2010 b","False",1268956800,1269388800],[227,"levant 2010 b","False",1265846400,1266192000]]]

这与我在这里看到的帖子完全不同:jQuery FullCalendar JSON date issue

(注意缺少标签信息和花括号)

有人可以向我解释我可能做错了什么以及为什么我的输出格式不正确。

TIA

【问题讨论】:

    标签: asp.net asp.net-mvc fullcalendar


    【解决方案1】:

    代码有小问题(可能是转换)....

    这个:

        Private Shared ReadOnly _supportedTypes As Type() = New () {GetType(Meeting)} 
    
    Public Overloads Overrides ReadOnly Property SupportedTypes() As IEnumerable(Of Type) 
        Get 
            Return _supportedTypes 
        End Get 
    End Property 
    

    在 VB.Net 中不可接受,在“= New ()”上显示错误

    正确的代码是什么?我尝试过简单地使用“= New Meeting”,但出现“'MVC.Meeting'类型的值无法转换为'System.Type'的一维数组”的错误。

    【讨论】:

    • 啊,那是因为它是一个内联数组构造函数。您需要删除 ` = New () {GetType(Meeting)} ` 位并将数组构造函数放入类的构造函数中。我会尝试修改我的答案以表明我的意思。
    • 看来是转换器。该行应显示为Private Shared ReadOnly _supportedTypes As Type() = New Type(-1) {GetType(Meeting)},尽管我不确定-1。我不太了解 VB.NET。
    • 再次感谢 CodeSleuth,不幸的是仍然有问题,所以最后一次询问我是否可以拥有您最初发布的原始 C#source 的副本,我将基于 MVC 部分C#中的系统。再次表示衷心的感谢。
    【解决方案2】:

    您不能只在对象上使用 JsonSerializer - 如您所见,它不是 FullCalendar 要求的正确格式。

    您需要提供自己的序列化程序(从 c# 转换而来):

    Public Class Meeting
        Public ID As Integer
        Public Title As Integer
        Public Start As DateTime
        Public [End] As DateTime
        Public AllDay As Boolean
    End Class
    
    Public Class MeetingJavaScriptConverter
        Inherits JavaScriptConverter
        Private Shared ReadOnly _supportedTypes As Type() = New Type(-1) {GetType(Meeting)}
        
        Public Overloads Overrides ReadOnly Property SupportedTypes() As IEnumerable(Of Type)
            Get
                Return _supportedTypes
            End Get
        End Property
        
        Public Overloads Overrides Function Serialize(ByVal obj As Object, ByVal serializer As JavaScriptSerializer) As IDictionary(Of String, Object)
            Dim meeting = TryCast(obj, Meeting)
            If meeting IsNot Nothing Then
                Dim dictionary = New Dictionary(Of String, Object)()
                
                dictionary.Add("id", meeting.ID)
                dictionary.Add("title", meeting.Title)
                dictionary.Add("start", meeting.Start.ToJson())
                dictionary.Add("end", meeting.[End].ToJson())
                
                dictionary.Add("allDay", If(meeting.AllDay, "true", "false"))
                
                Return dictionary
            End If
            Return New Dictionary(Of String, Object)()
        End Function
        
        Public Overloads Overrides Function Deserialize(ByVal dictionary As IDictionary(Of String, Object), ByVal type As Type, ByVal serializer As JavaScriptSerializer) As Object
            Throw New NotImplementedException()
        End Function
    End Class
    
    Public Module DateTimeExtensionMethods
        Private Sub New()
        End Sub
        <System.Runtime.CompilerServices.Extension> _
        Public Function ToJson(ByVal dateTime As DateTime) As String
            Return dateTime.ToString("s")
        End Function
    End Module
    

    从查询中填充Meeting 列表后,您可以按如下方式使用它:

    Dim serializer As New JavaScriptSerializer()
    serializer.RegisterConverters(New () {New MeetingJavaScriptConverter()})
    Dim jsonresult As String = serializer.Serialize(meetings.ToArray())
    

    (转换使用:http://www.developerfusion.com/tools/convert/csharp-to-vb/

    【讨论】:

    • 不用担心C#转换,可以做到。非常非常感谢快速响应和解决方案。非常感谢。
    • 嘿,没关系,使用那个网站转换它:) 我希望你能看到这对 JSON 结果有什么影响 - Dictionary&lt;string, object&gt; 在这里很重要。
    【解决方案3】:

    FAO CodeSleuth(以及其他需要此功能的人)。

    感谢你,你帮助我“理解”了这个问题,我现在可以正常工作了。

    我自己的代码如下:

        Function GetEvents(ByVal [start] As Double, ByVal [end] As Double) As JsonResult
        Dim sqlConnection As New SqlClient.SqlConnection
    
        sqlConnection.ConnectionString = My.Settings.sqlConnection
    
        Dim sqlCommand As New SqlClient.SqlCommand
        sqlCommand.CommandText = "SELECT tripID AS ID, tripName AS Title, dateStart AS [Start], dateEnd AS [End] FROM tblTrip WHERE userID=18 AND DateStart IS NOT NULL"
        sqlCommand.Connection = sqlConnection
    
        Dim ds As New DataSet
        Dim da As New SqlClient.SqlDataAdapter(sqlCommand)
        da.Fill(ds, "Meetings")
        sqlConnection.Close()
    
        Dim meetings = From c In ds.Tables("Meetings") Select {c.Item("ID"), c.Item("Title"), "False", c.Item("Start"), c.Item("End"), "False"}
    
        Dim meetingsArray As New ArrayList()
    
        For Each dr As DataRow In ds.Tables("Meetings").Rows
            Dim m As New Meeting
            With m
                .AllDay = False
                .End = CDate(dr.Item("End")).ToJson()
                .ID = dr.Item("ID")
                .Start = CDate(dr.Item("Start")).ToJson()
                .Title = dr.Item("Title")
            End With
            meetingsArray.Add(m)
        Next
    
        Return Json(meetingsArray, JsonRequestBehavior.AllowGet)
    
    
    End Function
    

    以及下面的类定义:

    Public Class Meeting
    Public id As Integer
    Public title As String
    Public start As String
    Public [end] As String
    Public allDay As Boolean
    

    结束类

    以及以下功能,再次感谢您:

    Public Module DateTimeExtensionMethods
    Sub New()
    End Sub
    <System.Runtime.CompilerServices.Extension()> _
    Public Function ToJson(ByVal dateTime As DateTime) As String
        Return dateTime.ToString("s")
    End Function
    

    结束模块

    效果很好,尽管我确实需要稍微调整它以从 Linq 结果中读取(或者只是将 SQL 命令更改为过滤器)。

    再次感谢您帮助我理解问题,我坚信人们需要理解,现在只需复制代码,您的帮助就完成了。

    杰森

    【讨论】:

      【解决方案4】:

      对不起,我之前简短检查时错过了您的评论。
      这是我回答的原始代码:

      public class Meeting
      {
          public int ID;
          public int Title;
          public DateTime Start;
          public DateTime End;
          public bool AllDay;
      }
      
      public class MeetingJavaScriptConverter : JavaScriptConverter
      {
          private static readonly Type[] _supportedTypes = new[] { typeof(Meeting) };
      
          public override IEnumerable<Type> SupportedTypes
          {
              get { return _supportedTypes; }
          }
      
          public override IDictionary<string, object> Serialize(
              object obj, JavaScriptSerializer serializer)
          {
              var meeting = obj as Meeting;
              if (meeting != null)
              {
                  var dictionary = new Dictionary<string, object>();
      
                  dictionary.Add("id", meeting.ID);
                  dictionary.Add("title", meeting.Title);
                  dictionary.Add("start", meeting.Start.ToJson());
                  dictionary.Add("end", meeting.End.ToJson());
      
                  dictionary.Add("allDay", meeting.AllDay ? "true" : "false");
      
                  return dictionary;
              }
              return new Dictionary<string, object>();
          }
      
          public override object Deserialize(IDictionary<string, object> dictionary,
              Type type, JavaScriptSerializer serializer)
          {
              throw new NotImplementedException();
          }
      }
      
      public static class DateTimeExtensionMethods
      {
          public static string ToJson(this DateTime dateTime)
          {
              return dateTime.ToString("s");
          }
      }
      

      以及用法(放在普通ASP.NET网站的Page_Load时):

      JavaScriptSerializer serializer = new JavaScriptSerializer();
      serializer.RegisterConverters(new[] { new MeetingJavaScriptConverter() });
      string jsonresult = serializer.Serialize(meetings.ToArray());
      
      Response.Clear();
      Response.ContentType = "text/javascript";
      Response.Write(jsonresult);
      Response.End();
      

      我粘贴了显示如何使 Page_Load 像 http 处理程序一样工作的额外代码,因为这是我使用它的方式。

      显然,您不必使用我编写的扩展方法(因为这只是我编写的,因为我使用了许多其他有用的不同 Json 序列化程序)。

      所以你去。这就是我所有的代码,这对我来说就像一个魅力。祝你好运! :)

      【讨论】:

      • 该死,我刚刚注意到你粘贴的答案。大声笑。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-27
      • 2013-03-31
      • 1970-01-01
      相关资源
      最近更新 更多