2008-11-24 84 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

编辑:代码高照明

相关问题