Skip to content Skip to sidebar Skip to footer

How To Pass Generic List From Code Behind To Javascript

Is it possible to pass the generic list of addresses to client side in java script? List data is availble at server side, i want to send the list to java script function which wil

Solution 1:

I'll be utilizing C# rather than Visual Basic, but you could essentially do this:

Code Behind:

JavaScriptSerializer serializer = newJavaScriptSerializer();
List<Address> deserialize = serializer.Deserialize<List<Address>>(address);
foreach(Address address in deserialize)
{
     // Do something with Exposed Properties:
}

The Address Class will be very, very basic:

publicclassAddress
{
     publicint Id { get; set; }
     publicstring Street { get; set; }
     publicstring City { get; set; }
     publicstring State { get; set; }
     publicstring Zip { get; set; }
}

That is essentially the backend, now all you have to do on the front-end is:

functionBuildAddress(Id,Street,City,State,Zip) {
     varaddress=null;item= {
          Id:Id,
          Street:Street,
          City:City,
          State:State,
          Zip:Zip
     };
}

A clean function to build our object. Now, we actually need to pass that content:

var address = newArray();
var convertAddress;

address.push(BuildAddress(id, street, city, state, zip));
convertedAddress = JSON.stringfy(address);

$.ajax({
     url: '<%= Page.ResolveUrl("~/Services/Location.aspx") %>'data: { Address: convertedAddress},
     type: 'POST',

     success: function (address) {
          var result = JSON.parse(address);
          // Do something with result, example: result[0].City
     }
});

That will pass the data in the manner your attempting. You'll have to play with it a bit though.

Post a Comment for "How To Pass Generic List From Code Behind To Javascript"