asp.net database application with ajax

In this tutorial, we will develop a complete asp.net web application with database functionality. We will also add ajax functionality in our application.

CREATION OF DATABASE

We create the internal database file with the visual studio. The database file is placed in the same application folder. The following are database tables:

Database Name: mydb.mdf

person

CREATE TABLE [dbo].[person] (
[id] INT IDENTITY (1, 1) NOT NULL,
[name] VARCHAR (50) NULL,
[age] INT NULL,
[address] VARCHAR (500) NULL,
PRIMARY KEY CLUSTERED ([id] ASC)
);

preferences

CREATE TABLE [dbo].[preferences] (
[prefid] VARCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([prefid] ASC)
);

person_pref

CREATE TABLE [dbo].[person_pref] (
[fpersonid] INT NOT NULL,
[fprefid] VARCHAR (50) NOT NULL,
CONSTRAINT [FK_person_pref_person] FOREIGN KEY ([fpersonid]) REFERENCES [dbo].[person] ([id]) ON DELETE CASCADE,
CONSTRAINT [FK_person_pref_preferences] FOREIGN KEY ([fprefid]) REFERENCES [dbo].[preferences] ([prefid]) ON DELETE CASCADE
);

CREATION OF A MASTER PAGE

The master page is used to define the layout/design of the website. In our master page we are defining a menu. In professional designs we also attach a style sheet in our master page (which we have not done to keep things simpler).

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

<!DOCTYPE html>

<html>
<head runat="server">
    <title></title>
    <asp:ContentPlaceHolder id="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Menu ID="Menu1" runat="server" BackColor="#FFFBD6" DynamicHorizontalOffset="2" Font-Names="Verdana" Font-Size="0.8em" ForeColor="#990000" Orientation="Horizontal" StaticSubMenuIndent="10px">
            <DynamicHoverStyle BackColor="#990000" ForeColor="White" />
            <DynamicMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" />
            <DynamicMenuStyle BackColor="#FFFBD6" />
            <DynamicSelectedStyle BackColor="#FFCC66" />
            <Items>
                <asp:MenuItem NavigateUrl="~/index.aspx" Text="LIST" Value="LIST"></asp:MenuItem>
                <asp:MenuItem Text="INSERT" Value="INSERT" NavigateUrl="~/insert.aspx"></asp:MenuItem>
                <asp:MenuItem Text="SEARCH" Value="SEARCH" NavigateUrl="~/search.aspx" ></asp:MenuItem>
            </Items>
            <StaticHoverStyle BackColor="#990000" ForeColor="White" />
            <StaticMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" />
            <StaticSelectedStyle BackColor="#FFCC66" />
        </asp:Menu>

    <div>
        <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
        
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
</html>

CREATION OF PAGE TO SHOW RECORDS FROM PERSON TABLE.

We create a page that shows record from person table into a GridView control. Since we want to apply the design of master page on this page, we go to File, New File, Web Form, and then check the option Master Page to enable the application of master page on our page.

index.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="index" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <script language="javascript" type="text/javascript">window.history.forward(1)</script>   
     <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
            DataKeyNames="id" DataSourceID="SqlDataSource1" 
            OnRowDataBound="GridView1_RowDataBound" AllowSorting="True" AllowPaging="True">

            <Columns>                
                <asp:TemplateField HeaderText="View">
                    <ItemTemplate>
                        <a href='view.aspx?id=<%# Eval("id")%>'>View</a>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True" SortExpression="id" />
                <asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
                <asp:BoundField DataField="address" HeaderText="address" SortExpression="address" />
                <asp:BoundField DataField="age" HeaderText="age" SortExpression="age" />
                <asp:TemplateField HeaderText="Subjects">
                    <ItemTemplate>
                        <asp:CheckBoxList ID="CheckBoxList1" runat="server" Enabled="false"  DataTextField="fprefid" DataValueField="fprefid">
                        </asp:CheckBoxList>
                        
                    </ItemTemplate>
                    
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Choices">
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# GetMyString( Eval("id") ) %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:mydbConnectionString %>" 
            SelectCommand="SELECT [id], [name], [age], [address] FROM [person]"></asp:SqlDataSource>
     <asp:Panel ID="Panel1" runat="server" Visible="False">
         <asp:Label ID="Label2" runat="server" Text="Showing result against search query"></asp:Label>
         &nbsp;<asp:Button ID="btnClear" runat="server" OnClick="btnClear_Click" Text="Clear Search Results" />
     </asp:Panel>
</asp:Content>

index.aspx.cs

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.Configuration;
using System.Data;

public partial class index : System.Web.UI.Page
{
    string constr;
    protected void Page_Load(object sender, EventArgs e)
    {
        constr = ConfigurationManager.ConnectionStrings["mydbConnectionString"].ConnectionString;

        if (Session["s_userid"] != null)
        {
            Response.Write(Session["s_userid"]);
            Response.Write("<br>");
            Response.Write(Session["s_name"]);
        }

        if (Session["s_query"]!=null)
        {
            Panel1.Visible = true;
            SqlDataSource1.SelectCommand = Session["s_query"].ToString();
            SqlDataSource1.DataBind();
        }

    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            CheckBoxList cbl = (CheckBoxList)e.Row.FindControl("CheckBoxList1");
            object objTemp = GridView1.DataKeys[e.Row.RowIndex].Value as object;
            string id = objTemp.ToString();

            SqlConnection con1 = new SqlConnection(constr);
            SqlConnection con2 = new SqlConnection(constr);
            SqlCommand com1 = new SqlCommand("select prefid from preferences", con1);

            if (con1.State == ConnectionState.Closed)
                con1.Open();

            if (con2.State == ConnectionState.Closed)
                con2.Open();

            SqlDataReader dreader1 = com1.ExecuteReader();



            if (dreader1.HasRows)
            {
                while (dreader1.Read())
                {
                    SqlCommand com2 = new SqlCommand("select fprefid from person_pref where fpersonid='" + id + "' and fprefid = '" + dreader1["prefid"] + "'", con2);
                    SqlDataReader dreader2 = com2.ExecuteReader();

                    ListItem li = new ListItem();

                    if (dreader2.HasRows)
                    {
                        li.Text = dreader1["prefid"].ToString();
                        li.Selected = true;
                    }
                    else
                    {
                        li.Text = dreader1["prefid"].ToString();
                        li.Selected = false;
                    }

                    cbl.Items.Add(li);
                    dreader2.Close();
                }
            }
            con1.Close();
            con2.Close();
        }

    }

    public string GetMyString(object val)
    {
        // This function is just showing how we can even assign custom values to controls placed in gridview.

        if (val.ToString() == "1")
            return "one";
        else if (val.ToString() == "2")
            return "two";
        else if (val.ToString() == "3")
            return "three";
        else
            return "hello";
    }

    protected void btnClear_Click(object sender, EventArgs e)
    {
        Session.Remove("s_query");
        Panel1.Visible = false;
        Response.Redirect("index.aspx");
    }
}

Next we create a page to show single record

view.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="view.aspx.cs" Inherits="view" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
    <style type="text/css">
        .auto-style1 {
            width: 100%;
            
        }
    </style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

    <asp:FormView ID="FormView1" runat="server" DataKeyNames="id" DataSourceID="SqlDataSource1" OnDataBound="FormView1_DataBound" OnItemUpdating="FormView1_ItemUpdating">
        <EditItemTemplate>
            <table class="auto-style1" border="1">
                <tr>
                    <td>id:</td>
                    <td>
                        <asp:Label ID="idLabel1" runat="server" Text='<%# Eval("id") %>' />
                    </td>
                </tr>
                <tr>
                    <td>name:</td>
                    <td>
                        <asp:TextBox ID="nameTextBox" runat="server" Text='<%# Bind("name") %>' />
                    </td>
                </tr>
                <tr>
                    <td>age:</td>
                    <td>
                        <asp:TextBox ID="ageTextBox" runat="server" Text='<%# Bind("age") %>' />
                    </td>
                </tr>
                <tr>
                    <td>Subjects</td>
                    <td>
                        <asp:CheckBoxList ID="CheckBoxListEdit1" runat="server" DataTextField="fprefid" DataValueField="fprefid" >
                        </asp:CheckBoxList>
                    </td>
                </tr>
                <tr>
                    <td>address:</td>
                    <td>
                        <asp:TextBox ID="addressTextBox" runat="server" Text='<%# Bind("address") %>' TextMode="MultiLine" />
                    </td>
                </tr>
              
            </table>
            <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="Update" />
            &nbsp;<asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" />
        </EditItemTemplate>
        
        <ItemTemplate>
            <table class="auto-style1" border="1">
                <tr>
                    <td>id:</td>
                    <td>
                        <asp:Label ID="idLabel" runat="server" Text='<%# Eval("id") %>' />
                    </td>
                </tr>
                <tr>
                    <td>name: </td>
                    <td>
                        <asp:Label ID="nameLabel" runat="server" Text='<%# Bind("name") %>' />
                    </td>
                </tr>
                <tr>
                    <td>age:</td>
                    <td>
                        <asp:Label ID="ageLabel" runat="server" Text='<%# Bind("age") %>' />
                    </td>
                </tr>
                <tr>
                    <td>Subjects</td>
                    <td>
                        <asp:CheckBoxList ID="CheckBoxList1" runat="server" DataTextField="fprefid" DataValueField="fprefid" Enabled="false">
                        </asp:CheckBoxList>
                    </td>
                </tr>
                <tr>
                    <td>address: </td>
                    <td>
                        <asp:TextBox ID="addressLabel" runat="server" TextMode="MultiLine" ReadOnly="true" Text='<%# Bind("address") %>' />
                    </td>
                </tr>
            </table>            
            <asp:LinkButton ID="EditButton" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit" />
            &nbsp;<asp:LinkButton ID="DeleteButton" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete" />
            
        </ItemTemplate>
    </asp:FormView>
    <br />
    <asp:Label ID="LabelError" runat="server" ></asp:Label><br />
    <asp:Button ID="btnBack" Text="BACK" runat="server" PostBackUrl="~/index.aspx" />
    <asp:Label ID="lblId" runat="server" Visible="False"></asp:Label>
    <br />
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:mydbConnectionString %>" SelectCommand="SELECT id, name, age, address FROM person WHERE (id = @id)" DeleteCommand="DELETE FROM person WHERE (id = @id)" UpdateCommand="UPDATE person SET name = @name, age=@age, address=@address WHERE (id = @id)">
        <DeleteParameters>
            <asp:Parameter Name="id" />
        </DeleteParameters>
        <SelectParameters>
            <asp:QueryStringParameter Name="id" QueryStringField="id" />
        </SelectParameters>
        <UpdateParameters>
            <asp:Parameter Name="name" />
            <asp:Parameter Name="age" />
            <asp:Parameter Name="address" />
            <asp:Parameter Name="id" />
        </UpdateParameters>
    </asp:SqlDataSource>

    </asp:Content>

view.aspx.cs

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.Configuration;
using System.Data;

public partial class view : System.Web.UI.Page
{
    string constr;
    protected void Page_Load(object sender, EventArgs e)
    {
        constr = ConfigurationManager.ConnectionStrings["mydbConnectionString"].ConnectionString;
    }

    protected void FormView1_DataBound(object sender, EventArgs e)
    {


        // For Readonly mode
        if (FormView1.CurrentMode == FormViewMode.ReadOnly)
        {
            if (FormView1.DataItem != null)
            {
                Label Label1 = FormView1.FindControl("idLabel") as Label;

                CheckBoxList cbl = (CheckBoxList)FormView1.FindControl("CheckBoxList1");

                string id = Label1.Text;
                lblId.Text = id;

                SqlConnection con1 = new SqlConnection(constr);
                SqlConnection con2 = new SqlConnection(constr);
                SqlCommand com1 = new SqlCommand("select prefid from preferences", con1);

                if (con1.State == ConnectionState.Closed)
                    con1.Open();

                if (con2.State == ConnectionState.Closed)
                    con2.Open();

                SqlDataReader dreader1 = com1.ExecuteReader();



                if (dreader1.HasRows)
                {
                    while (dreader1.Read())
                    {
                        SqlCommand com2 = new SqlCommand("select fprefid from person_pref where fpersonid='" + id + "' and fprefid = '" + dreader1["prefid"] + "'", con2);
                        SqlDataReader dreader2 = com2.ExecuteReader();

                        ListItem li = new ListItem();

                        if (dreader2.HasRows)
                        {
                            li.Text = dreader1["prefid"].ToString();
                            li.Selected = true;
                        }
                        else
                        {
                            li.Text = dreader1["prefid"].ToString();
                            li.Selected = false;
                        }

                        cbl.Items.Add(li);
                        dreader2.Close();
                    }
                }
            }
        }
        else if (FormView1.CurrentMode == FormViewMode.Edit)
                {
                    if (FormView1.DataItem != null)
                    {
                       // Label Label1 = FormView1.FindControl("idLabel") as Label;

CheckBoxList cbl = (CheckBoxList)FormView1.FindControl("CheckBoxListEdit1");

                string id = lblId.Text;

                        SqlConnection con1 = new SqlConnection(constr);
                        SqlConnection con2 = new SqlConnection(constr);
                        SqlCommand com1 = new SqlCommand("select prefid from preferences", con1);

                        if (con1.State == ConnectionState.Closed)
                            con1.Open();

                        if (con2.State == ConnectionState.Closed)
                            con2.Open();

                        SqlDataReader dreader1 = com1.ExecuteReader();



                        if (dreader1.HasRows)
                        {
                            while (dreader1.Read())
                            {
                                SqlCommand com2 = new SqlCommand("select fprefid from person_pref where fpersonid='" + id + "' and fprefid = '" + dreader1["prefid"] + "'", con2);
                                SqlDataReader dreader2 = com2.ExecuteReader();

                                ListItem li = new ListItem();

                                if (dreader2.HasRows)
                                {
                                    li.Text = dreader1["prefid"].ToString();
                                    li.Selected = true;
                                }
                                else
                                {
                                    li.Text = dreader1["prefid"].ToString();
                                    li.Selected = false;
                                }

                                cbl.Items.Add(li);
                                dreader2.Close();
                            }
                        }
                    }
                }
        

    }

    protected void FormView1_ItemUpdating(object sender, FormViewUpdateEventArgs e)
    {
        SqlConnection con = new SqlConnection(constr);
        SqlCommand com = new SqlCommand("delete from person_pref where fpersonid=@fpersonid", con);
        com.Parameters.AddWithValue("@fpersonid", lblId.Text);

        try
        {
            con.Open();
            com.ExecuteNonQuery();           
        }
        catch(SqlException ex)
        {
            Response.Write(ex.Message);
        }
       
        CheckBoxList cbl = (CheckBoxList)FormView1.FindControl("CheckBoxListEdit1");

        foreach (ListItem li in cbl.Items)
        {
            if (li.Selected == true)
            {
                com = new SqlCommand("insert into person_pref(fpersonid,fprefid) values(@fpersonid,@fprefid)", con);
                com.Parameters.AddWithValue("@fpersonid", lblId.Text);
                com.Parameters.AddWithValue("@fprefid", li.Text);
                com.ExecuteNonQuery();
            }
        }

        con.Close();
    }
}

Next we create a page to insert record in database

insert.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="insert.aspx.cs" Inherits="insert" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <script language="javascript" type="text/javascript">window.history.forward(1)</script>   

    <table border="1">
        <tr>
            <td>Name</td><td>
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>Age</td><td>
            <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>Address</td><td>
            <asp:TextBox ID="TextBox3" runat="server" TextMode="MultiLine"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>Preferences</td><td>
            <asp:CheckBoxList ID="CheckBoxList1" runat="server" DataSourceID="SqlDataSource1" DataTextField="prefid" DataValueField="prefid">
            </asp:CheckBoxList>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:mydbConnectionString %>" SelectCommand="SELECT [prefid] FROM [preferences]"></asp:SqlDataSource>
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <asp:Label ID="Label1" runat="server"></asp:Label>
            </td>
        </tr>
        <tr>
            <td>&nbsp;</td><td>
            <asp:Button ID="btnInsert" runat="server" OnClick="btnInsert_Click" Text="INSERT" />
            <asp:Button ID="btnReset" runat="server" Text="RESET" OnClick="btnReset_Click" />
            </td>
        </tr>
    </table>
</asp:Content>

insert.aspx.cs

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.Configuration;
using System.Drawing;

public partial class insert : System.Web.UI.Page
{
    string constr;
    
    protected void Page_Load(object sender, EventArgs e)
    {

        constr = ConfigurationManager.ConnectionStrings["mydbConnectionString"].ConnectionString;

        
    }

    protected void btnInsert_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(constr);

        // In the below query, we are also getting the ID of last record inserted.
        SqlCommand com = new SqlCommand("insert into person(name,age,address) values(@name, @age, @address) SELECT SCOPE_IDENTITY()", con);

        com.Parameters.AddWithValue("@name",TextBox1.Text);
        com.Parameters.AddWithValue("@age",TextBox2.Text);
        com.Parameters.AddWithValue("@address",TextBox3.Text);

        int lastInsertId = 0;
        bool success = false;
        try
        {
            con.Open();
            lastInsertId = Convert.ToInt32(com.ExecuteScalar());
            //com.ExecuteNonQuery();
            

            success = true;
            Label1.Text = "Record inserted";
            Label1.ForeColor = Color.Green;
        }
        catch(SqlException ex)
        {
            Label1.Text = ex.Message;
            Label1.ForeColor = Color.Red;
        }
        finally
        {
            
        }

        if(success == true)
        {
           foreach(ListItem li in CheckBoxList1.Items)
            {
                if(li.Selected == true)
                { 
                com = new SqlCommand("insert into person_pref(fpersonid,fprefid) values(@fpersonid,@fprefid)", con);
                com.Parameters.AddWithValue("@fpersonid", lastInsertId);
                com.Parameters.AddWithValue("@fprefid", li.Text);
                com.ExecuteNonQuery();
                    
                }
            }
            con.Close();
            Response.Redirect("index.aspx");
        }
        

    }

    protected void btnReset_Click(object sender, EventArgs e)
    {
        Response.Redirect("insert.aspx");
    }
}

We create a page to login a user

login.aspx

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
<link rel="stylesheet" href="bootstrap-4.0.0-beta.2-dist/css/bootstrap.min.css">  
<script src="jquery/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="bootstrap-4.0.0-beta.2-dist/js/bootstrap.bundle.min.js"></script>

</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table>
                <tr>
                    <td>User Name</td>
                    <td>
                        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>Name</td>
                    <td>
                        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>&nbsp;</td>
                    <td>
                        <asp:Button ID="btnLogin" CssClass="btn btn-success" runat="server" Text="Login" OnClick="btnLogin_Click" />
                       
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>

login.aspx.cs

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.Configuration;

public partial class login : System.Web.UI.Page
{
    string constr;
    protected void Page_Load(object sender, EventArgs e)
    {
        constr = ConfigurationManager.ConnectionStrings["mydbConnectionString"].ConnectionString;
    }

    protected void btnLogin_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(constr);
        SqlCommand com = new SqlCommand("select * from person where id=@id and name=@name", con);
        com.Parameters.AddWithValue("@id", TextBox1.Text.Trim());
        com.Parameters.AddWithValue("@name", TextBox2.Text.Trim());
        con.Open();
        SqlDataReader dr = com.ExecuteReader();
        String id = "";
        if (dr.HasRows)
        {
            /*
            while(dr.Read())
            {
               id= dr["id"].ToString();
            }
            */
            Session["s_userid"] = TextBox1.Text;
            Session["s_name"] = TextBox2.Text;
            dr.Close();
            con.Close();
            Response.Redirect("index.aspx");

        }


    }
}

Finally we want to integrate ajax in our application. Here is first example:

ajaxexample1.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="ajaxexample1.aspx.cs" Inherits="ajaxexample1" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">


    <asp:ScriptManager ID="ScriptManager1" runat="server">
            </asp:ScriptManager>


    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
            
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
  
      <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />


    </ContentTemplate>
    
  
    
    </asp:UpdatePanel>


</asp:Content>

 

ajaxexample1.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ajaxexample1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        TextBox1.Text = "Pakistan";
    }
}

And here another example in which we are using ajax enabled GridView

ajaxexample2.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="ajaxexample2.aspx.cs" Inherits="ajaxexample2" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:mydbConnectionString %>" SelectCommand="SELECT [id], [name], [age], [address] FROM [person]"></asp:SqlDataSource>
    
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
    <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" BackColor="White" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4" DataKeyNames="id" DataSourceID="SqlDataSource1">
        <Columns>
            <asp:CommandField ShowSelectButton="True" />
            <asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True" SortExpression="id" />
            <asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
            <asp:BoundField DataField="age" HeaderText="age" SortExpression="age" />
            <asp:BoundField DataField="address" HeaderText="address" SortExpression="address" />
        </Columns>
        <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
        <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
        <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
        <RowStyle BackColor="White" ForeColor="#330099" />
        <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
        <SortedAscendingCellStyle BackColor="#FEFCEB" />
        <SortedAscendingHeaderStyle BackColor="#AF0101" />
        <SortedDescendingCellStyle BackColor="#F6F0C0" />
        <SortedDescendingHeaderStyle BackColor="#7E0000" />
    </asp:GridView>

    </ContentTemplate>
    </asp:UpdatePanel>

</asp:Content>

ajaxexample2.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ajaxexample2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

 

The complete application can be downloaded from THIS LINK

Add a Comment

Your email address will not be published. Required fields are marked *