返回JSON结果与对象名称MVC [英] Returning Json Result with object name MVC

查看:168
本文介绍了返回JSON结果与对象名称MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当一个JSON结果是由控制器对象名称似乎缺少回来后,我通常不会介意,但Flexbox的jQuery插件需要以特定的格式JSON结果。

When a json result is returned by the controller the object name seems to be missing, I normally wouldn't mind but the flexbox jquery plugin requires the json result in a particular format.

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"}  
 ]} 

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

控制器code

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

JSON结果返回(缩短)

[{"Id":"2010","Name":"2010"},{"Id":"2009","Name":"2009"},{"Id":"2008","Name":"2008"}]

期望的结果(缩短)

{"results": [{"Id":"2010","Name":"2010"},{"Id":"2009","Name":"2009"},{"Id":"2008","Name":"2008"}]}

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

推荐答案

在C#中,你可以使用一个匿名对象来调整其出路JSON结构:

In C#, you can use an anonymous object to tweak the JSON structure on its way out:

// 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});

更新:

从演,这是同样的事情VB语法:

From Dien, this is the VB syntax for the same thing:

Return Json(New With {Key .results = yearSelectList}, JsonRequestBehavior.AllowGet)

这篇关于返回JSON结果与对象名称MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆