Click here to Skip to main content
Click here to Skip to main content

Example Of JavaScript Serializer And Json String Using WebMethod

, 18 Oct 2013
Rate this:
Please Sign up or sign in to vote.
Simple example of using JavaScript Serializer in webmethod and consuming in client side using jquery

Introduction

The tip helps in calling the server side method from client side using jquery, creating a json string in web method and displaying in the front end with the required interval.

Background

I have used basic Jquery in my projects. In my present project, I got an idea of appending the values from server side to front end but without post-back and in certain interval of time. This is just an example, it can be changed as per the requirement.

Using the Code

The HTML part of the example consists of a div which will be appended by the string receiving from the web method.

 <div id="Display">
 </div> 

And in the code behind, I have used an XML to load the data to the DataTable. When the certain interval expires, the web method returns the 1st row from the DataTable and returns successive rows for the next same intervals .

The Jquery code is shown below:

 function getajax(i) {
                $.ajax({
                    type: "POST",
                    url: "default.aspx/createjson",
                    data: "{'i':'" + i + "'}",
                    contentType: "application/json; charset=utf-8",
                    datatype: "json",
                    success: function (data) {
                        var jsonostr = data.d;
                        var jsonobj = eval('(' + jsonostr + ')');
                        for (i in jsonobj) {
                            $("#Display").append
                            ("<span>City Id - " + jsonobj[i]["id"] + 
                            "</span>&nbsp;<span>City Name - " + 
                            jsonobj[i]["name"] + "</span><br/>");

                        }

                    },
                    error: function () {  inter = 1; }
                });

            } 

This function get the data row of index passed to the code behind (Web Method) "i" is the index here and appends the row to the div with id="Display".

To get the data row at same intervals of time, I have used the set Interval function of the JavaScript. The code is shown below:

 var inter = 1;
            setInterval(function () {
                getajax(inter);
                inter = inter + 1;
            }, 1000); 

In the code behind, the Web method is used to fetch the XML data to data table, get selected row or passed index row and returns it in the form of generic-list to the client-side using JavaScriptSerializer to serialize the generic list.

A temporary class is declared to store the data in the form of the required format. The code is shown below:

 [WebMethod]
    public static string createjson(string i)
    {
        DataSet cityds = new DataSet();
        cityds.ReadXml(HttpContext.Current.Server.MapPath("~/xml/cities.xml"));
        DataTable citydt = cityds.Tables[0];

        citydt = citydt.Rows.Cast<DataRow>().Skip(int.Parse(i) - 1).Take(1).CopyToDataTable();


        // citydt.AsEnumerable().Take(int.Parse(i));
        JavaScriptSerializer cityjson = new JavaScriptSerializer();
        List<loadvals> cityjsonlst = new List<loadvals>();
        loadvals cityrow;
        foreach (DataRow citydr in citydt.Rows)
        {
            cityrow = new loadvals();
            cityrow.id = citydr["id"].ToString();
            cityrow.name = citydr["name"].ToString();

            cityjsonlst.Add(cityrow);
        }
        return cityjson.Serialize(cityjsonlst);
    } 
 private class loadvals
    {
        public string id { get; set; }
        public string name { get; set; }
    } 

And don't forget to add the namespace System.Web.Script.Serialization;

I hope this will be helpful for the beginner.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Nandakishore G N
Software Developer Canarys Automation Pvt Ltd
India India
Software Engineer in Canarys Automation Pvt Ltd, Bangalore, India.
 
My Blog gnnrao.blogspot.in

Comments and Discussions

 
GeneralIf you do not want to use Serializer PinmemberMehul M Thakkar17-Oct-13 23:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140814.1 | Last Updated 18 Oct 2013
Article Copyright 2013 by Nandakishore G N
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid