我正在使用博文中的DynamicJsonModelBinder
将我的JSON数据从JavaScript传递到我的ASP.NET MVC控制器DynamicJsonObject
。
查看博文:http://blog.duc.as/2011/06/07/making-mvc-3-a-little-more-dynamic/
我将我的项目转换为VB.NET:http://pastebin.com/p3cfHSab。
Imports System.Dynamic
Imports System.Web.Helpers
Namespace MyNameSpace
Public Class TestController
Inherits System.Web.Mvc.Controller
Function Index(<DynamicJson()> obj As DynamicJsonObject) As ActionResult
Dim output As String = ""
Dim members As IEnumerable(Of String) = obj.GetDynamicMemberNames()
For Each item In members
output += item + vbCrLf
Next
Return Content(output)
End Function
End Class
End Namespace
客户方:
var jsonObject = { "ID": "123", "NAME": "Mr. Rosema", "TEST": "123"};
$.ajax({
url: "/Test",
type: "POST",
contentType: "application/json",
data:
JSON.stringify(jsonObject)
,
success: function (data) {
}
});
这很有效。在我的控制器中,我可以像这样访问我的jsonObject:obj.ID '123
但我还没有想到如何遍历所有属性。我可以将所有成员名称作为IEnumerable字符串集合(obj.GetDynamicMemberNames()
),但如何使用TryGetMember方法来访问成员的值?
答案 0 :(得分:1)
你可以做的是创建一个类,然后将json序列化到你的类中。
Class Info
public property ID as integer
public property NAME as string
public property TEST as string
end class
控制器代码:
Function Index(byval input as Info) As ActionResult
Return Content(input.NAME)
End Function
客户端代码:
var jsonObject = {"input": { "ID": "123", "NAME": "Mr. Rosema", "TEST": "123"}};
$.ajax({
url: "/Test",
type: "POST",
contentType: "application/json",
data: JSON.stringify(jsonObject),
success: function (data) {
}
});