gpt4 book ai didi

asp.net-mvc - 返回对象名称为 MVC 的 Json 结果

转载 作者:行者123 更新时间:2023-12-03 18:27:39 25 4
gpt4 key购买 nike

当 Controller 返回 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"}
]}

类(class)
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

Controller 代码
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 结构:

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

更新:

从 Dien,这是同一件事的 VB 语法:
Return Json(New With {Key .results = yearSelectList}, JsonRequestBehavior.AllowGet)

关于asp.net-mvc - 返回对象名称为 MVC 的 Json 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4042929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com