2008-11-24 35 views
8

我正在使用FlexiGrid jQuery插件,我需要從我的MVC應用程序中取回一個JSON對象,如果FlexiGrid只取對象,但我需要向響應字符串添加幾個項目才能正常工作與FlexiGrid。我怎樣才能得到一個JsonResult對象作爲一個字符串,所以我可以修改它?

因此,這裏是我的控制器代碼的一部分:

If Request.QueryString("json") IsNot Nothing Then 
    Dim data As New StringBuilder() 
    data.Append("page: " & pageIndex & "," & vbCrLf) 
    data.Append("total: " & ViewData.TotalCount & "," & vbCrLf) 
    data.Append("rows: ") 
    data.Append(Json(objCustomerList)) 

    Return Content(data.ToString()) 
End If 

不幸的是在上面的代碼Json(objCustomerList)返回「System.Web.MVV.JsonResult」,而不是所期望的JSON字符串數據。我也嘗試Json(objCustomerList).ToString()只是爲了看看會發生什麼,以及同樣的事情。

任何想法?

回答

2

我結束了modifiying CodeProject上的例子有點:

Imports System.Web.Script.Serialization 
Imports System.Reflection 

Public Class FlexiGrid 

    Public Class FlexigridRow 
     Public id As String 
     Public cell As New List(Of String)() 
    End Class 

    Public Class FlexigridObject 
     Public page As Integer 
     Public total As Integer 
     Public rows As New List(Of FlexigridRow)() 
    End Class 

    Public Shared Function GetFlexiGridJSON(ByVal page As Integer, ByVal total As Integer, ByVal o As Object) As String 

     Dim js As New JavaScriptSerializer 
     Dim flexiGrid As New FlexigridObject 
     Dim i As Integer = 0 
     flexiGrid.page = page 
     flexiGrid.total = total 

     For Each c In o 
      Dim r As New FlexigridRow() 
      r.id = i 
      r.cell = GetPropertyList(c) 
      flexiGrid.rows.Add(r) 
      i += i 
     Next 

     Return js.Serialize(flexiGrid) 
    End Function 

    Private Shared Function GetPropertyList(ByVal obj As Object) As List(Of String) 

     Dim propertyList As New List(Of String)() 

     Dim type As Type = obj.[GetType]() 
     Dim properties As PropertyInfo() = type.GetProperties(BindingFlags.Instance Or BindingFlags.[Public]) 
     For Each [property] As PropertyInfo In properties 
      Dim o As Object = [property].GetValue(obj, Nothing) 
      propertyList.Add(If(o Is Nothing, "", o.ToString())) 
     Next 

     Return propertyList 

    End Function 

End Class 

現在在我的控制器,我只要致電:

Return Content(GetFlexiGridJSON(pageIndex, TotalCount, objCustomerList)) 

只要我傳遞的對象是對象的列表它的工作原理完美。

15

Json() ASP.NET MVC中的方法只是通過JsonResult類使用JavaScriptSerializer類。如果您想將使用JSON的objCustomerList對象序列化爲字符串,您可以自己使用它。

我的建議是採取稍微不同的方法。

  • 創建一個表示您試圖創建的JavaScript對象的.NET等價物的模型。也許FlexiGridModel對象具有Page,Total,Rows和CustomerList屬性。
  • 然後,當您將FlexiGridModel傳遞到Json()時,它就會工作,無需使用StringBuilder構建JSON字符串。

如果你只是想你的代碼工作有一個override on JavaScriptSerializer.Serialize()是採用序列化對象和StringBuilder的結果追加到。這應該是你正在尋找的。

一些相關鏈接:

+0

正是我需要的。感謝勺子和計算器 – Hcabnettek 2010-11-18 18:48:34

10

你也可以這樣做:

JsonResult json = ... ; 
JavaScriptSerializer serializer = new JavaScriptSerializer(); 
string yourJsonResult = serializer.Serialize(json.Data); 

就這麼簡單:d

編輯:代碼高照明

相關問題