Вопрос

I am using a method of passing Json to and from my markup using jquery and ajax. This can be described in more detail on this page: http://blogs.telerik.com/aspnet-ajax/posts/12-04-27/the-present-and-future-of-using-json-in-webforms.aspx

In this snippet of code, I try to set the object's value dynamically by setting a string variable named "test" to a business object's value:

       Dim objOrder As Object = New JsonObject()
       For Each Order As BoVendorOrder In Orders
            Dim Vendor As New BoVendor(Order.VendorID)
            Dim test As String = Order.VendorOrderID
            objOrder.test = Vendor.VendorName + " - " + Order.VendorOrderPoNumber
       Next

I left out some code for the sake of brevity. The goal is to get the objOrder.test to be equal to the VendorOrderID (a number in our SQL database) so that the JSON looks like this:

       {
            "123456": "VendorName - PONumber",
            "678901": "VendorName - PONumber"
       }

Any of you guys out there know how to do this?

Это было полезно?

Решение

Do you really need the order IDs to be properties of the object? It might be easier to just return a serialized Dictionary(Of String, String). You could still look up by order ID and it would be easier to loop over than the props of the Javascript object.

Here's an example of what you'd need to do using the dictionary approach:

Dim OrdersDict as New Dictionary(Of String, String)()  
For Each Order as BoVendorOrder In Orders  
    If Not OrdersDict.ContainsKey(Order.VendorOrderID) Then  
        OrdersDict.Add(Order.VendorOrderID, Vendor.VendorName + " - " + Order.VendorOrderPoNumber)
    End If
Next

' Serialize the dictionary object to JSON

' Using System.Web.Script.Serialization.JavascriptSerializer:
Dim Serializer As New JavaScriptSerializer
If MaxLength Then Serializer.MaxJsonLength = Int32.MaxValue
Dim x as String = Serializer.Serialize(OrdersDict) 'Return or response.write x as needed

'or

'Using JSON.net
Dim x as String = JsonConvert.SerializeObject(OrdersDict) 'Return or response.write x as needed
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top