Pass a Generic List Array from codebehind to client-side using JSON.

Here’s an example. aspx file.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script src="Scripts/jtemplates.js" type="text/javascript"></script>
    <script src="Scripts/jquery.min.js" type="text/javascript"></script>
    <script src="Scripts/json2.min.js" type="text/javascript"></script>
</head>
<body>
 <form id="form1" runat="server">
 <script type="text/javascript">
   //Traditional Javascript way
    for (var i = 0; i < player.length; i++) {
       var t1 = player[i];
    }
   //efficient-&-compact JQuery way
   $(player).each(function (index, person) {
        alert('AddressID: ' + person.AddressID +
      ' AddressLine1: ' + person.AddressLine1 +
      ' City: ' + person.City
        );
   });
 </script>

<div>
</div>

</form>
</body>
</html>

codebehind file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Text;

using System.Web.Script.Serialization;

public partial class ArrayJSONSerializeDeSerialize : System.Web.UI.Page
{
    public class AddressInfo
    {
        public int AddressID { get; set; }
        public string AddressLine1 { get; set; }
        public string City { get; set; }
        public string PostalCode { get; set; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ConvertToJSON();
        }
    }

    private static List<AddressInfo> CreateGenericArray()
    {
        List<AddressInfo> _AddressInfo = new List<AddressInfo>();
        DataTable dt = GetData();
        foreach (DataRow dr in dt.Rows)
        {
            AddressInfo lp = new AddressInfo();
            lp.AddressID = int.Parse(dr["AddressID"].ToString());
            lp.AddressLine1 = dr["AddressLine1"].ToString();
            lp.City = dr["City"].ToString();
            lp.PostalCode = dr["PostalCode"].ToString();
            _AddressInfo.Add(lp);
        }
        return _AddressInfo;
    }

    private static DataTable GetData()
    {
        SqlDataReader reader = null;
        DataTable dt = new DataTable();
        using (SqlConnection conn = new SqlConnection())
        {
            conn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnStr2"].ConnectionString;
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "SELECT  AddressID, AddressLine1, City, PostalCode FROM [AdventureWorks].[Person].[Address] where AddressLine1 like '105%' ORDER BY AddressID";
                cmd.Connection = conn;
                StringBuilder sb = new StringBuilder();
                conn.Open();
                reader = cmd.ExecuteReader();
                dt.Load(reader);
                conn.Close();
            }
        }
        return dt;
    }

    public void ConvertToJSON()
    {
        JavaScriptSerializer jss1 = new JavaScriptSerializer();
        string _myJSONstring = jss1.Serialize(CreateGenericArray());
        string player = "var player="+_myJSONstring+";";
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "player123", player, true);
    }
}

Advertisements
This entry was posted in JQuery. Bookmark the permalink.

4 Responses to Pass a Generic List Array from codebehind to client-side using JSON.

  1. arun says:

    Good work!!!

  2. Balaji B says:

    Excellent work dude.. I was searching like mad for this solution…. A million thanks

  3. Vitthal says:

    Really valuable……Thank you so much……

  4. Nandini says:

    Thanks a lot :)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s