Click here to Skip to main content
Click here to Skip to main content
Go to top

Ajax

, 5 Mar 2009
Rate this:
Please Sign up or sign in to vote.
The objective behind writing this article is to make use of Ajax Control Toolkit in implementation.
Ajax_All_In_1

Introduction

The objective behind writing this article is to make use of Ajax Control Toolkit in implementation. Here I have tried to create a three layer architecture by using ObjectDataSource. In an application, suppose we want to do an edit and delete GridView row on the client side. So here, I present the easiest way around Ajax Control Toolkit to do client side data modification.

Background

Earlier I too faced lots of problem and was unable to work out of how to handle anything JUST after an update of update panel. So I planned to write up a demo as soon I had some time. Please feel free to post any comments, bugs or suggestions for improvement.

Key Scenario

Use of:

  • Ajax Control Toolkit
  • Three layer architecture
  • ObjectDataSource 
  • JavaScript

Implementation of Three Layer Architecture 

Now let's start making the things in a real world application. Create a database layer named DBClass.cs where we are going to define the various fields and methods:

Under DBClass.cs class file, create the following:

public class DBClass
{
    private SqlConnection con = new SqlConnection();
    private SqlCommand com = new SqlCommand();
    private SqlDataAdapter da = new SqlDataAdapter();

    public DBClass()
	{
		//
		// Default Constructor
		//
	}
    private void setConnectionState()
    {
        if (con.State == System.Data.ConnectionState.Open)
        {
            con.Close();
        }
        con.ConnectionString = ConfigurationSettings.AppSettings["sqlCon"];
        con.Open();
    }

    public SqlCommand setCommand(string SP_Name)
    {
        setConnectionState();
        com = new SqlCommand(SP_Name, con);
        com.CommandType = System.Data.CommandType.StoredProcedure;
        return com;
    }

    public SqlDataAdapter setAdapter(string SP_Name)
    {
        setConnectionState();

        da = new SqlDataAdapter(SP_Name, con);
        da.SelectCommand.CommandType = System.Data.CommandType.StoredProcedure;
        return da;
    }
}

Now create a Client.cs where we are going to define the various fields, properties and methods:

Under Client.cs class file, create the following fields:

    private int CustomerID;
    private string CompanyName;
    private string ContactName;
    private string ContactTitle;
    private string Address;
    private string City;
    private string PostalCode;
    private string Country;
    private string Phone;
    private string Fax;

//create the following constructor:

    public Client()
	{
		//
		// Default constructor
		//
	}

    public Client(int customerID, string companyName, string contactName,
                  string contactTitle, string address, string city, string postalCode, 
                  string country, string phone,string fax)
    {
        this.CustomerID = customerID;
        this.CompanyName = companyName;
        this.ContactName = contactName;
        this.ContactTitle = contactTitle;
        this.Address = address;
        this.City = city;
        this.PostalCode = postalCode;
        this.Country = country;
        this.Phone = Phone;
        this.Fax = fax;
    }

//create properties for each class field like the following:

    public int customerID
    {
        get
        {
            return this.CustomerID;
        }
        set
        {
            this.CustomerID = value;
        }
    }

//create method for class like the following

    [DataObjectMethod(DataObjectMethodType.Select)]
    public static DataSet GetAllClient()
    {
        DataSet ds = new DataSet();
        try
        {
            DBClass db = new DBClass();
            SqlDataAdapter da = db.setAdapter("GetAllCustomers");
            da.Fill(ds);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
      
        return ds;
    }

    [DataObjectMethod(DataObjectMethodType.Fill)]
    public static DataSet ClientLoadByID(int CustomerID)
    {
        DataSet ds = new DataSet();
        try
        {
            DBClass db = new DBClass();
            SqlDataAdapter da = db.setAdapter("GetCustomerByID");
            da.SelectCommand.Parameters.Add
		(new SqlParameter("@CustomerID", CustomerID));
            da.Fill(ds);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
        return ds;
    }

   [DataObjectMethod(DataObjectMethodType.Delete)]
    public static bool ClientDelete(int CustomerID)
    {

        try
        {
            DBClass db = new DBClass();
            SqlCommand com = db.setCommand("DeleteCustomerByID");
            com.Parameters.Add(new SqlParameter("@CustomerID", CustomerID));
            com.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
        return true;
    }

    [DataObjectMethod(DataObjectMethodType.Update)]
    public static bool ClientUpdate(Client cust)
    {
        try
        {
            DBClass db = new DBClass();
            SqlCommand com = db.setCommand("CustomerUpdate");
            com.Parameters.Add(new SqlParameter("@CustomerID", cust.CustomerID));
            com.Parameters.Add(new SqlParameter("@CompanyName", cust.companyName));
            com.Parameters.Add(new SqlParameter("@ContactName", cust.contactName));
            com.Parameters.Add(new SqlParameter("@ContactTitle", cust.contactTitle));
            com.Parameters.Add(new SqlParameter("@Address", cust.address));
            com.Parameters.Add(new SqlParameter("@City", cust.city));
            com.Parameters.Add(new SqlParameter("@PostalCode", cust.postalCode));
            com.Parameters.Add(new SqlParameter("@Country", cust.country));
            com.Parameters.Add(new SqlParameter("@Phone", cust.phone));
            com.Parameters.Add(new SqlParameter("@Fax", cust.fax));
            com.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
        return true;
    }

AjaxComponentArtStyle.aspx

This page contains two update Panels. In the first update Panel, I have GridView and in the second update Panel, I have a DetailsView.

ASP.NET UpdatePanel control enables you to build rich, client-centric Web applications. By using UpdatePanel controls, you can refresh selected parts of the page instead of refreshing the whole page with a postback. This is referred to as performing a partial-page update. An ASP.NET Web page that contains a ScriptManager control and one or more UpdatePanel controls can automatically participate in partial-page updates, without custom client script.

ScriptManager

The ScriptManager control manages client script for Microsoft ASP.NET AJAX pages. By default, the ScriptManager control registers the script for the Microsoft AJAX Library with the page. This enables client script to use the type system extensions and to support features such as partial page rendering and Web-service calls.

<form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
   <div>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
           <asp:GridView ID="gvCustomers" runat="server" DataSourceID="odsCustomerList">

           // Here we will add columns and template column fields             

           </asp:GridView>
        </ContentTemplate>
    </asp:UpdatePanel>
   </div>
</form>

ObjectDataSource

The ASP.NET ObjectDataSource control represents a middle-tier object with data retrieval and update capabilities.The ObjectDataSource control acts as a data interface for data-bound controls such as the GridView, FormView or DetailsView controls. You can use these controls to display and edit data from a middle-tier business object on an ASP.NET Web page.

Here I took two ObjectDataSource to fill GridView and for DetailsView:

<asp:ObjectDataSource ID="odsCustomerList" runat="server" TypeName="Client" 
             SelectMethod="GetAllClient" DeleteMethod="ClientDelete">             
</asp:ObjectDataSource>
        
<asp:ObjectDataSource ID="odsCustomerDetail" runat="server" TypeName="Client" 
           DataObjectTypeName="Client" OnSelecting="OdsCustomerDetail_Selecting" 
           SelectMethod="ClientLoadByID" UpdateMethod="ClientUpdate">            
</asp:ObjectDataSource>

ModalPopupExtender

It pops up a modal form on the screen with whatever you want to see, prompting the user to perform some action.

<ajax:ModalPopupExtender ID="mdlPopup" runat="server"
          TargetControlID="btnShowPopup" 
          PopupControlID="pnlPopup" CancelControlID="btnClose"
          BackgroundCssClass="modalBackground" />

DetailsView 

The DetailsView control displays a single record from a data source, where each data row represents a field in the record. It is often used in combination with a GridView control for master/detail scenarios.

<asp:DetailsView ID="dvCustomerDetail" runat="server"
          DataSourceID="odsCustomerDetail" CssClass="detailgrid" 
          GridLines="None" DefaultMode="Edit" AutoGenerateRows="false"
          Visible="false" Width="100%">
    <Fields>
     
    // Here we will add Bound field and template field to edit a row

    </Fields>
</asp:DetailsView>

Progress Bar

  <ajax:UpdatePanelAnimationExtender ID="UPAnimation" runat="server"
        TargetControlID="updatePanel">
                <Animations>
                    <OnUpdating>
                        <Parallel duration="0">
                            <%-- place the update progress div over the
                                gridview control --%>
                            <ScriptAction Script="onUpdating();" />  
                         </Parallel>
                    </OnUpdating>
                    <OnUpdated>
                        <Parallel duration="0">
                            <%--find the update progress div and place it
                                over the gridview control--%>
                            <ScriptAction Script="onUpdated();" /> 
                        </Parallel> 
                    </OnUpdated>
                </Animations>
            </ajax:UpdatePanelAnimationExtender>            
          
            <asp:Panel ID="Panel1" runat="server" CssClass="progress_bar"
                style="display:none;">
                <div class="container">
                    <div class="header">      Loading, please wait...</div>
                    <div class="body"><br />
                        <img src="Images/Indicater.gif" />
                    </div>
                </div>
            </asp:Panel>

Using the Code

To use this code, download the related zip file and create a database named AjaxDB and run the given script in that. Then create a virtual directory for the application, and change your server in web.config as shown below: 

  <appSettings>
    <add key="sqlCon"
    value="data source=SARFARAZ-0923B2\SQLEXPRESS;initial catalog=AjaxDB;
     integrated security=True"/>
  </appSettings>

History

  • 5th March, 2009: Initial post

About the Author

Ashish Singh Parihar has done Master of Computer Application from IPS Academy Indore, Madhya Pradesh, India. He is currently working in a S/W company as a team lead at Indore for more than 1 year. He has over 2 years of experience. He has also done Bachelor Degree in BSc(PCM). He loves working with Microsoft Technology. He has stared with C, then C++, then moved to .NET 1.1 and then .NET 2.0. He is currently working with C#, ASP.NET, Enterprise application Block, Active Directory, WSS (Windows SharePoint Server), DotNetNuke. He loves Programming in C#. He is also a Microsoft Gold Certified Technology Specialist on Web Development. His hobbies include listening to music and developing his own small tools and utilities.

License

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

Share

About the Author

ashishparihar1310
Team Leader Stem Infotech
India India
No Biography provided

Comments and Discussions

 
Generalmissing graphic PinmemberDonsw9-Apr-09 6:28 
GeneralTitle of article PinmemberSteven Berkovitz7-Mar-09 8:03 
GeneralRe: Title of article PinmemberShoki9-Mar-09 6:39 

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.140916.1 | Last Updated 5 Mar 2009
Article Copyright 2009 by ashishparihar1310
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid