Monday, December 5, 2011

Data Linking with jQuery [ Add Update Show with jQuery ]


Recently, Microsoft announced three jQuery plugins as Official plugin.
  • jQuery Client Templating
  • Data linking
  • Globalisation
In my last article, I discussed about jQuery Templating. You can view that article here. So I think, you all must find the Templating article very useful. Because, by the time web applications development is evolving, we are moving towards Client side development/scripting, to provide fast and very trendy/flashy look and feel.
So in this article, I am going to discuss another very cool feature, i.e. Data linking. This helps us link the data and the UI.

EditPerson.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="EditPerson.aspx.cs" Inherits="EditPerson" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Edit Person</title>
    <script type="text/javascript" language="javascript" src="Scripts/jquery-1.4.2.js" ></script>
    <script type="text/javascript" language="javascript" src="Scripts/jQuery.datalink.js" ></script>
    <script language="javascript" type="text/javascript">
        var person = {};
        //Linking the controls from the object
        $(document).ready(function() {
         $(person)
        .linkBoth('Name', '#txtName', 'val')
        .linkBoth('Age', '#txtAge', 'val')
        .linkBoth('SSN', '#txtSSN', 'val')
        .linkBoth('Gender', '#txtGender', 'val')
        .linkBoth('ContactNo', '#txtCNo', 'val')


        });
    // To fetch the detail from the server of the entert person name
    function PopulatePersonDetails() {
        var inputs = new Object();
        inputs.name = document.getElementById('txtPersonName').value;
       
        $.ajax({
            type: "POST",
            url: "EditPerson.aspx/GetPerson",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(inputs),
            dataType: "json",
            success: AjaxSucceeded,
            error: AjaxFailed
        }); 
    }
    //This function get the global variable person object
    //which is always sync with with UI and sends it
    //to server to add/update
    function UpdateorAddData() {
        var inputs = new Object();
        inputs.person = JSON.stringify(person);
        $.ajax({
            type: "POST",
            url: "EditPerson.aspx/AddUpdatePerson",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(inputs),
            dataType: "json",
            success: ShowStatus,
            error: AjaxFailed
        }); 


        }
        //This function is to show the status whether a new person is added or updated
        function ShowStatus(result) {
            alert(result.d);
        }
        //To be called when ajax call succeeded
        //If no object will be found, it'll show an error message as 'Person Not found'
        //else call update the person object
        function AjaxSucceeded(result) {
            if (result.d == 'null')
                alert('Person Not found');
            else
                $(person).attr(JSON.parse(result.d));
        }
        //Will be called, if ajax call gets failed somehow.
        function AjaxFailed(result) {
            alert('Ajax failed');
        }


        function ShowUpdatedData() {
            alert([person.Name,person.Age,person.SSN,person.Gender,person.ContactNo]);
        }
    
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td> Name </td>
                <td>
                    <input id="txtPersonName" type="text" />
                    <input id="Button1" type="button" value="GetPersonDetails" onclick="PopulatePersonDetails();"/>
                </td>
            </tr>
            <tr>
                <td colspan="3"> <b>Person Details</b></td>
            </tr>
            <tr>
                <td>Name</td>
                <td><input id="txtName" type="text" /></td>
            </tr>
            <tr>
                <td>Age</td>
                <td><input id="txtAge" type="text" /></td>
            </tr>
            <tr>
                <td>SSN</td>
                <td><input id="txtSSN" type="text" /></td>
            </tr>
            <tr>
                <td>Gender</td>
                <td><input id="txtGender" type="text" /></td>
            </tr>
            <tr>
                <td>Contact Number</td>
                <td><input id="txtCNo" type="text" /></td>
            </tr>
            <tr>
                <td colspan="2">
                    <input id="Button3" type="button" value="Show Updated JS Object" onclick="ShowUpdatedData();"/>
                    <input id="Button2" type="button" value="Add/Update Person" onclick="UpdateorAddData();"/>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>


EditPerson.aspx.cs

using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Web.Services;

public partial class EditPerson : System.Web.UI.Page
{
    public static List<Person> lstPerson = null;
    protected void Page_Load(object sender, EventArgs e)
    {
    }
   
    [WebMethod()]
    public static string GetPerson(string name)
    {
        InitializePersons();
        JavaScriptSerializer ser = new JavaScriptSerializer();
        // ser.Serialize(persons);
        return ser.Serialize(lstPerson.Find(p => p.Name == name));
    }

    [WebMethod()]
    public static string AddUpdatePerson(string person)
    {
        string status;
        JavaScriptSerializer ser = new JavaScriptSerializer();
        Person obj = ser.Deserialize<Person>(person);
        InitializePersons();
        Person per = lstPerson.Find(p => p.SSN == obj.SSN);
        if (per == null)
        {
            lstPerson.Add(obj);
            status = "New person added";
        }
        else
        {
            // Updating the person
            lstPerson.Remove(per);
            lstPerson.Add(obj);
            status = "Person updated";
        }
      
        // ser.Serialize(persons);
        return status;
    }

    public static void InitializePersons()
    {
        if (lstPerson == null)
        {
            lstPerson = new List<Person>()
            {
                new Person { Age = 27, Name= "Brij", Gender="Male", ContactNo="123456789", SSN="CC123456"},
                new Person { Age = 18, Name = "Ravi", Gender = "Male", ContactNo = "987654321", SSN="AB654321"}
            };
        }
    }
   
}








No comments :

Post a Comment