Wednesday 20 November 2013

Example Of JavaScript Serializer And Json String Using WebMethod

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.

Html part  


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

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

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); 


Code Behind



1. 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 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.



[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);
    } 


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

private class loadvals
    {
        public string id { get; set; }
        public string name { get; set; }
    }

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


I hope this will be helpful for the beginner.

First published in codeproject.com on 18-oct-2013 - view here
Download example here

By Nandakishorerao
Trainee software engineer In Canarys automation Pvt Ltd.
Bangalore

Example of gridview rowcommand on Button Click

Introduction


One of the most used controls in my projects is Gridview. Therefore, I thought of writing a tip which has been used in my projects frequently.  

Background  


Gridview displays the value of a data source in a table. Here, I am going to give an example of using an event called "RowCommand". The RowCommand is raised when a buttonLinkButton or ImageButton is clicked in the Gridview Control.

Html part 

 

In the HTML part , I have binded the values which have to be displayed on the page.
And in the code behind, I have used an XML to load the data to the gridview. When the button is clicked, the event verifies for the command name and command argument.
And, then, I have just alerted the name of the user in this example. Changes can be made according to the requirement.

<asp:GridView ID="gridMembersList" AutoGenerateColumns="False" GridLines="None" 
  runat="server" onrowcommand="gridMembersList_RowCommand">
        <Columns>
        <asp:TemplateField HeaderText="User Name">
        <ItemTemplate>
            <asp:Literal ID="ltrlName" runat="server" Text='<%# Eval("Name") %>'></asp:Literal>
            <asp:Literal ID="ltrlSlno" runat="server" Visible="False" Text='<%# Eval("Id") %>'></asp:Literal>
        </ItemTemplate>
        </asp:TemplateField>
        
        <asp:TemplateField HeaderText="View More">
        <ItemTemplate>
            <asp:Button ID="btnViewmore" CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" CommandName="More" runat="server" Text="View More" /></ItemTemplate>
 </asp:TemplateField> </Columns></asp:GridView>  


Code Behind


1. Populating the gridview in Page_Load event from xml file "Member Details"

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string pathofxml = Server.MapPath("xml/MemberDetails.xml");
            DataSet ds = new DataSet();
            ds.ReadXml(pathofxml);
            gridMembersList.DataSource = ds;
            gridMembersList.DataBind();
        }
    }


2. In the code behind of the GridView_RowCommand event is  fetching the name of the member and alerting the name of the clicked row. 

protected void gridMembersList_RowCommand(object sender, GridViewCommandEventArgs e)
   {
        if (e.CommandName == "More")
        {
            int index = Convert.ToInt32(e.CommandArgument.ToString());
            Literal ltrlslno = (Literal)gridMembersList.Rows[index].FindControl("ltrlSlno");
            Literal ltrlName = (Literal)gridMembersList.Rows[index].FindControl("ltrlName");
            ScriptManager.RegisterStartupScript(this, this.GetType(), 
            "Message", "alert('" + ltrlName.Text+ "');", true);
        }
    } 



First published in codeproject.com on 30-march-2013 - view here
Download example here

By Nandakishorerao
Trainee software engineer In Canarys automation Pvt Ltd.
Bangalore