返回对象名称为MVC的Json Result

All*_*cus 4 vb.net asp.net-mvc json

当控制器返回json结果时,对象名称似乎丢失了,我通常不介意,但flexbox jquery插件需要特定格式的json结果.

Flexcombobox预期的格式

{"results":[  
     {"id":"1","name":"Ant"},  
     {"id":"2","name":"Bear"},  
     {"id":"3","name":"Cat"},  
     {"id":"4","name":"Dog"},  
     {"id":"5","name":"Elephant"},  
     {"id":"6","name":"Fox"},  
     {"id":"7","name":"Guinea Pig"},  
     {"id":"8","name":"Horse"},  
     {"id":"9","name":"Iguana"},  
     {"id":"10","name":"Jaguar"}  
 ]} 
Run Code Online (Sandbox Code Playgroud)

Public Class FlexboxResult

    Private _id As String
    Public Property Id() As String
        Get
            Return _id
        End Get
        Set(ByVal value As String)
            _id = value
        End Set
    End Property

    Private _name As String
    Public Property Name() As String
        Get
            Return _name
        End Get
        Set(ByVal value As String)
            _name = value
        End Set
    End Property

End Class
Run Code Online (Sandbox Code Playgroud)

控制器代码

Function PartYearsList() As JsonResult
            Dim yearSelectList As List(Of FlexboxResult) = New List(Of FlexboxResult)

            For index As Integer = DateTime.Now.Year To 1955 Step -1
                yearSelectList.Add(New FlexboxResult() With {.Id = index, .Name = index})
            Next

            Return Me.Json(yearSelectList.ToArray(), JsonRequestBehavior.AllowGet)
End Function
Run Code Online (Sandbox Code Playgroud)

Json结果返回(缩短)

[{"Id":"2010","Name":"2010"},{"Id":"2009","Name":"2009"},{"Id":"2008","Name":"2008"}]
Run Code Online (Sandbox Code Playgroud)

期望的结果(缩短)

{"results": [{"Id":"2010","Name":"2010"},{"Id":"2009","Name":"2009"},{"Id":"2008","Name":"2008"}]}
Run Code Online (Sandbox Code Playgroud)

Flexcombobox文档 http://www.fairwaytech.com/flexbox.aspx

Dav*_*ard 16

在C#中,您可以使用匿名对象在其出路时调整JSON结构:

// The ToArray() probably isn't necessary. Collections like List<T> are treated
//  as JavaScript arrays when JavaScriptSerializer turns them into JSON.
return Json(new { results = yearSelectList});
Run Code Online (Sandbox Code Playgroud)

更新:

从Dien,这是同一件事的VB语法:

Return Json(New With {Key .results = yearSelectList}, JsonRequestBehavior.AllowGet)
Run Code Online (Sandbox Code Playgroud)

  • 对于那些对VB代码感兴趣的人.返回Json(New With {Key .results = yearSelectList},JsonRequestBehavior.AllowGet) (2认同)