Tag: ASP.NET AJAX

Adding images to slideshow using a database

We can use a database to load image name and order to display. This kind of method eliminates to renaming images in a specific way and changing the application code. Therefore we do not have to rebuild and redeploy the application. We use Microsoft SQL Server 2014 as our database server.

Steps in Microsoft SQL Server Management Studio

  1. Create a database named Sample
  2. Create a table called tblImageData
  3. Insert images name and their order into tblImageDatatable
  4. Create a stored procedure named spGetImageData to get data of all images

Sample query in Microsoft SQL Server Management Studio

--create the database
create database Sample;

--create the table
create table tblImageData
(
 Id int identity(1, 1) primary key,
 Name nvarchar(50),
 [Order] int
)

--insert image data into the table
insert into tblImageData values ('Chrysanthemum.jpg', 1)
insert into tblImageData values ('Desert.jpg', 2)
insert into tblImageData values ('Hydrangeas.jpg', 3)
insert into tblImageData values ('Jellyfish.jpg', 4)
insert into tblImageData values ('Koala.jpg', 5)
insert into tblImageData values ('Lighthouse.jpg', 6)
insert into tblImageData values ('Penguins.jpg', 7)
insert into tblImageData values ('Tulips.jpg', 8)
insert into tblImageData values ('Welcome.jpg', 9)

--create the stored procedure
create proc spGetImageData
as
begin
 select *
 from tblImageData
end

We have to add connection string into the Web.config file.

<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.;Initial Catalog=Sample;Integrated Security=SSPI"
providerName="System.Data.SqlClient" />
</connectionStrings>

Then we need to add another WebForm called DatabaseImageSlideShow.aspx but it is much like the previous WebForm XmlImageSlideShow.aspx.

Sample code in DatabaseImageSlideShow.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DatabaseImageSlideShow.aspx.cs" Inherits="AjaxWebApplication.DatabaseImageSlideShow" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="1000" OnTick="Timer1_Tick"></asp:Timer>
<asp:Image ID="Image1" runat="server" Height="200" Width="200" />

Image Displaying: <asp:Label ID="lblImageName" runat="server" Text="Label"></asp:Label>

Image Order: <asp:Label ID="lblImageOrder" runat="server" Text="Label"></asp:Label>

<asp:Button ID="Button1" runat="server" Text="Stop slideshow" OnClick="Button1_Click" />
</ContentTemplate>
</asp:UpdatePanel></div>
</form>
</body>
</html>

Small changes have to be applied to the code behind file of this WebForm.

Steps in DatabaseImageSlideShow.aspx.cs

  1. we have to add two additional namespaces which are Configuration and System.Data.SqlClient.
  2. we have to replace
ds.ReadXml(Server.MapPath("~/Data/ImageData.xml"));

using

string cs = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
SqlDataAdapter da = new SqlDataAdapter("spGetImageData", con);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.Fill(ds, "image");

Sample code in DatabaseImageSlideShow.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;
using System.Configuration;
using System.Data.SqlClient;

namespace AjaxWebApplication
{
public partial class DatabaseImageSlideShow : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SetImageUrl();
}
}

protected void Timer1_Tick(object sender, EventArgs e)
{
int i = (int)ViewState["ImageOrder"];
i++;
ViewState["ImageOrder"] = i;

DataRow dr = ((DataSet)ViewState["ImageData"]).Tables["image"].Select().FirstOrDefault(x => x["order"].ToString() == i.ToString());

if (dr != null)
{
Image1.ImageUrl = "~/OriginalImages/" + dr["name"].ToString();
lblImageName.Text = dr["name"].ToString();
lblImageOrder.Text = dr["order"].ToString();
}
else
{
SetImageUrl();
}
}

protected void Button1_Click(object sender, EventArgs e)
{
if (Timer1.Enabled)
{
Timer1.Enabled = false;
Button1.Text = "Start slideshow";
}
else
{
Timer1.Enabled = true;
Button1.Text = "Stop slideshow";
}
}

private void SetImageUrl()
{
DataSet ds = new DataSet();
string cs = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
SqlDataAdapter da = new SqlDataAdapter("spGetImageData", con);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.Fill(ds, "image");
ViewState["ImageData"] = ds;
ViewState["ImageOrder"] = 1;

DataRow dr = ds.Tables["image"].Select().FirstOrDefault(x => x["order"].ToString() == "1");
Image1.ImageUrl = "~/OriginalImages/" + dr["name"].ToString();
lblImageName.Text = dr["name"].ToString();
lblImageOrder.Text = dr["order"].ToString();
}
}
}

Now you can have the slideshow as same as in the previous post. If you want to add a new image into the slide show you need to add it to OriginalImages folder and then you need to insert that image details into tblImageData table. That is all you want to do. You can download the source code from GitHub using https://github.com/hasiabewardana/ExperimentalAjaxWebApplication link. Hey hey! we are stopping here. Stay tuned with us.

 

Adding images to slideshow using XML file

Up to now we have created an image slideshow with 8 images which are named in a specific way such as 1.jpg, 2.jpg…8.jpg. You can see implementation details of that one in the previous post. But there are two problems we have to face.

  • We have to rename the original image in a specific way. (ex. 1.jpg)
  • If we want to add another image to the slideshow, we need to change the application code therefore it is required to rebuild and redeploy the application.

We can solve this problem using a XML file. XML file is a configuration file. Therefore we can update it without rebuilding the application. The reason is that it is a configuration file.

Steps in the AjaxWebApplication

  1. First we need to add another folder named OriginalImages to the root of the project.
  2. Paste images to that folder with their original names.
  3. Then we need to add another folder called Data to the root of the project.
  4. Add a XML file named ImageData.xml into that Data folder
  5. Add root element named images and within that, add child elements named image with attribute name and order in ImageData.xml file as below.
  6. Add another WebForm called XmlImageSlideShow.

Sample code in XmlImageSlideShow.aspx

<?xml version="1.0" encoding="utf-8" ?>
<images>
<image name="Chrysanthemum.jpg" order="1"/>
<image name="Desert.jpg" order="2"/>
<image name="Hydrangeas.jpg" order="3"/>
<image name="Jellyfish.jpg" order="4"/>
<image name="Koala.jpg" order="5"/>
<image name="Lighthouse.jpg" order="6"/>
<image name="Penguins.jpg" order="7"/>
<image name="Tulips.jpg" order="8"/>
</images>

Steps in XmlImageSlideShow.aspx

  1. Add ScriptManager control into the div tag of the form. Remember to add this inside the form tag always.
  2. Add UpdatePanel control under ScriptManager control inside the div
  3. Add ContentTemplate tag inside the UpdatePanel.
  4. Add a Timer control within that ContentTemplate tag and set the interval as 1000ms.
  5. Add Image control under Timer control inside the ContentTemplate tag and set attribute Height and Width as 200.
  6. Add text Image Displaying: followed by Label control named lblImageName under Image control inside the ContentTemplate
  7. Add text Image Order: followed by Label control named lblImageOrder under lblImageName Label control inside the ContentTemplate
  8. Add a Button control to control the image sequence.

Sample code in XmlImageSlideShow.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="XmlImageSlideShow.aspx.cs" Inherits="AjaxWebApplication.XmlImageSlideShow" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="1000" OnTick="Timer1_Tick"></asp:Timer>
<asp:Image ID="Image1" runat="server" Height="200" Width="200" />

Image Displaying: <asp:Label ID="lblImageName" runat="server" Text="Label"></asp:Label>

Image Order: <asp:Label ID="lblImageOrder" runat="server" Text="Label"></asp:Label>

<asp:Button ID="Button1" runat="server" Text="Stop slideshow" OnClick="Button1_Click" />
</ContentTemplate>
</asp:UpdatePanel></div>
</form>
</body>
</html>

Steps in XmlImageSlideShow.aspx.cs

  1. Create a private method named SetImageUrl.
  2. Within that method, create a DataSet You need to add System.Data namespace at the top of the file.
  3. Read XML file and store the result in the created DataSet
  4. Store that DataSet object in a ViewState[“ImageData”].
  5. Create another ViewState variable as ViewState[“ImageOrder”] and set 1 as the order.
  6. Get image data which has the 1 as the order into a DataRow.
  7. Using that result set ImageUrl property of Image1 control and Text property of lblImageName and lblImageOrder
  8. Call SetImageUrl method from Page_Load event if it is not a postback.
  9. Add the Tick event handler.
  10. Within that Tick event, get ViewState[“ImageOrder”] and increment it by 1, then update ViewState[“ImageOrder”] with new value.
  11. Get image data using updated order value and store it in a DataRow
  12. If that DataRoW object is not null, set ImageUrl property of Image1 control and Text property of lblImageName and lblImageOrder
  13. Else, call SetImageUrl
  14. Add Click event handler for the Button control and if the Timer control is always enabled, disable it and set the Text property of that Button control as “Start slideshow”. If the Timer is disabled, enable it and set the Text property of that Button control as “Stop slideshow”.

Sample code in XmlImageSlideShow.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;

namespace AjaxWebApplication
{
public partial class XmlImageSlideShow : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SetImageUrl();
}
}

protected void Timer1_Tick(object sender, EventArgs e)
{
int i = (int)ViewState["ImageOrder"];
i++;
ViewState["ImageOrder"] = i;

DataRow dr = ((DataSet)ViewState["ImageData"]).Tables["image"].Select().FirstOrDefault(x => x["order"].ToString() == i.ToString());

if (dr != null)
{
Image1.ImageUrl = "~/OriginalImages/" + dr["name"].ToString();
lblImageName.Text = dr["name"].ToString();
lblImageOrder.Text = dr["order"].ToString();
}
else
{
SetImageUrl();
}
}

protected void Button1_Click(object sender, EventArgs e)
{
if (Timer1.Enabled)
{
Timer1.Enabled = false;
Button1.Text = "Start slideshow";
}
else
{
Timer1.Enabled = true;
Button1.Text = "Stop slideshow";
}
}

private void SetImageUrl()
{
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("~/Data/ImageData.xml"));
ViewState["ImageData"] = ds;
ViewState["ImageOrder"] = 1;

DataRow dr = ds.Tables["image"].Select().FirstOrDefault(x => x["order"].ToString() == "1");
Image1.ImageUrl = "~/OriginalImages/" + dr["name"].ToString();
lblImageName.Text = dr["name"].ToString();
lblImageOrder.Text = dr["order"].ToString();
}
}
}

After running the project you can see the browser window as following.

8th image

 

If you want add another image you have to add it to the OriginalImages folder and then you need to update the ImageData.xml file as below.

<?xml version="1.0" encoding="utf-8" ?>
<images>
<image name="Chrysanthemum.jpg" order="1"/>
<image name="Desert.jpg" order="2"/>
<image name="Hydrangeas.jpg" order="3"/>
<image name="Jellyfish.jpg" order="4"/>
<image name="Koala.jpg" order="5"/>
<image name="Lighthouse.jpg" order="6"/>
<image name="Penguins.jpg" order="7"/>
<image name="Tulips.jpg" order="8"/>
<image name="Welcome.jpg" order="9"/>
</images>

You do not need to rebuild and redeploy the project. You can see the slideshow with 9th image as below.

9th image

 

You have the ability to control the sequence of the slideshow using the button control. You can download the source code from GitHub using https://github.com/hasiabewardana/ExperimentalAjaxWebApplication link. You will see more posts on exciting topics soon. Until then stay tuned with us.

Creating sequence image slideshow

We have designed a random image slideshow in our previous post. Today we are going to create a sequence image slideshow that means the slideshow starting from the first image and then keep displaying next image according to the name of the image. We named all images as 1.jpg, 2.jpd…8.jpg which are in Images folder of the root. In addition to that we are expecting add a feature to control the sequence using a Button control. Follow the below steps to achieve this.

Steps in SequenceImageSlideShow.aspx

  1. Add another WebForm called SequenceImageSlideShow.
  2. Add ScriptManager control into the div tag of the form. Remember to add this inside the form tag always.
  3. Add UpdatePanel control under ScriptManager control inside the div
  4. Add ContentTemplate tag inside the UpdatePanel.
  5. Add a Timer control within that ContentTemplate tag and set the interval as 1000ms.
  6. Add Image control under Timer control inside the ContentTemplate tag and set attribute Height and Width as 200.
  7. Add text ImageDisplaying: followed by Label control under Image control inside the ContentTemplate
  8. Add a Button control to control the image sequence.

Sample code in SequenceImageSlideShow.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SequenceImageSlideShow.aspx.cs" Inherits="AjaxWebApplication.SequenceImageSlideShow" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="1000" OnTick="Timer1_Tick"></asp:Timer>
<asp:Image ID="Image1" runat="server" Height="200" Width="200" />

Image Displaying: <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

<asp:Button ID="Button1" runat="server" Text="Stop slideshow" OnClick="Button1_Click" />
</ContentTemplate>
</asp:UpdatePanel></div>
</form>
</body>
</html>

Note that the WebForm is working on a stateless protocol therefore we need to have a ViewState variable to store the previous image name in the sequence.

Steps in SequenceImageSlideShow.aspx.cs

  1. Create a private method named SetImageUrl.
  2. Within that method check the ViewState Here we are using ViewState[“ImageDisplayed”] as the ViewState variable.
  3. If it is null, set ImageUrl property of Image control as “~/Images/1.jpg”, ViewState[“ImageDisplayed”] as 1 and Text property of Label control as “1.jpg”.
  4. Else again check the ViewState variable and if it is equal to 8, reset all the properties as in the step 3.
  5. If it is not equal to 8 increment the value of the ViewState and set all the properties of Image and Label controls with the updated value.
  6. Call SetImageUrl method from Page_Load event if it is not a postback.
  7. Add the Tick event handler and call SetImageUrl method from it.
  8. Add Click event handler for the Button control and if the Timer control is always enabled, disable it and set the Text property of that Button control as “Start slideshow”. If the Timer is disabled, enable it and set the Text property of that Button control as “Stop slideshow”.

Sample code in SequenceImageSlideShow.aspx.cs

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

namespace AjaxWebApplication
{
    public partial class SequenceImageSlideShow : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                SetImageUrl();
            }
        }

        protected void Timer1_Tick(object sender, EventArgs e)
        {
            SetImageUrl();
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if(Timer1.Enabled)
            {
                Timer1.Enabled = false;
                Button1.Text = "Start slideshow";
            }
            else
            {
                Timer1.Enabled = true;
                Button1.Text = "Stop slideshow";
            }
        }

        private void SetImageUrl()
        {
            if(ViewState["ImageDisplayed"] == null)
            {
                Image1.ImageUrl = "~/Images/1.jpg";
                ViewState["ImageDisplayed"] = 1;
                Label1.Text = "1.jpg";
            }
            else
            {
                int i = (int)ViewState["ImageDisplayed"];
                if (i == 8)
                {
                    Image1.ImageUrl = "~/Images/1.jpg";
                    ViewState["ImageDisplayed"] = 1;
                    Label1.Text = "1.jpg";
                }
                else
                {
                    i++;
                    Image1.ImageUrl = "~/Images/" + i.ToString() + ".jpg";
                    ViewState["ImageDisplayed"] = i;
                    Label1.Text = i.ToString() + ".jpg";
                }
            }
        }
    }
}

You can see the output windows as following. Before click the Button:

timer enabled

After button is clicked:

timer disabled

After button is clicked again:

timer enabled again

Now you have the control of the sequence of the image slideshow. You can stop the sequence in a position that you want and you can start the slideshow again. You can download the source code from GitHub using https://github.com/hasiabewardana/ExperimentalAjaxWebApplication link. You will see awesome posts in the future. Until then stay tuned with us.

Creating random image slideshow

Today we are going to apply our ASP.NET AJAX knowledge to create an image slideshow which is displaying images in a random sequence. To keep things simple we are trying to use step by step process from here. We can use the project that was used in the previous post.

Steps in RandomImageSlideShow.aspx

  1. Add a folder named Images to the root of the project and past 8 images into it which are having jpg, 2.jpg… up to 8.jpg.
  2. Add another WebForm called RandomImageSlideShow.
  3. Add ScriptManager control into the div tag of the form. Remember to add this inside the form tag always.
  4. Add UpdatePanel control under ScriptManager control inside the div
  5. Add ContentTemplate tag inside the UpdatePanel.
  6. Add a Timer control within that ContentTemplate tag and set the interval as 1000ms.
  7. Add Image control under Timer control inside the ContentTemplate tag and set attribute Height and Width as 200.
  8. Add text ImageDisplaying: followed by Label control under Image control inside the ContentTemplate We renamed that label as lblImageDisplaying.

Sample code in RandomImageSlideShow.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="RandomImageSlideShow.aspx.cs" Inherits="AjaxWebApplication.RandomImageSlideShow" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="1000" OnTick="Timer1_Tick"></asp:Timer>
<asp:Image ID="Image1" runat="server" Height="200" Width="200" />

ImageDisplaying: <asp:Label ID="lblImageDisplaying" runat="server" Text="Label"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel></div>
</form>
</body>
</html>

Steps in RandomImageSlideShow.aspx.cs

  1. Create a private named SetImageUrl.
  2. Within that method create an object of Random
  3. Generate a random number from 1 to 8 using Next method of the Random object and get that random number into an integer variable called i.
  4. Set the ImageUrl property in Image control using the above random number for the image file name.
  5. Set the Text property of the Label control using that random number as the image file name.
  6. Call SetImageUrl method from Page_Load event if it is not a postback.
  7. Add the Tick event handler and call SetImageUrl method from it.

Sample code in RandomImageSlideShow.aspx.cs

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

namespace AjaxWebApplication
{
    public partial class RandomImageSlideShow : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                SetImageUrl();
            }
        }

        protected void Timer1_Tick(object sender, EventArgs e)
        {
            SetImageUrl();
        }

        private void SetImageUrl()
        {
            Random ran = new Random();
            int i = ran.Next(1, 8);

            Image1.ImageUrl = "~/Images/" + i.ToString() + ".jpg";
            lblImageDisplaying.Text = i.ToString() + ".jpg";
        }
    }
}

random image slideshow

You can see an image slideshow as a random sequence as in above image. It can see simply because the Label prints the currently displaying image. You can download the source code from GitHub using https://github.com/hasiabewardana/ExperimentalAjaxWebApplication link. To see more on ASP.NET AJAX stay tuned with us.

ASP.NET AJAX Sample Implementation

We use Microsoft Visual Studio 2015 for creating this ASP.NET AJAX enabled web application. And we use .NET Framework 4.5.2 here.

Go to File -> New -> Project and then the following window will appear.

new project dialog

Then select Installed -> Templates -> Visual C# -> Web. Among three templates again select ASP.NET Web Application as in above dialog. We can give a suitable name for the solution and project that we are going to create. Here we give ExperimentalAjaxWebApplication for both solution name and project name. Then click OK. After that we can see the created web application. Its folder structure and all the files can be seen in Solution Explorer as below.

solution explorer

Here we do not have to manually add ASP.NET AJAX Control Toolkit instead visual studio has been added all stuff for us. We can see all things for Microsoft AJAX in Scripts -> WebForms -> MSAjax folder in the Solution Explorer as below.

ms ajax

In the Toolbox AJAX Server Controls can be seen as below.

ajax extensions

We need to add a new WebForm. To do that right click on the project name in Solution Explorer, select Add -> New Item -> WebForm. We give it a name called AjaxPartialPageUpdate. Then we need to set that newly created WebFrom as the start page therefore, right click on the name of the WebForm in the Solution Explorer, select Set As Start Page.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AjaxPartialPageUpdate.aspx.cs" Inherits="AjaxWebApplication.AjaxPartialPageUpdate" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div></div>
</form>
</body>
</html>

This WebForm only has a div tag, therefore we need to add three labels and one button control into that div tag.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AjaxPartialPageUpdate.aspx.cs" Inherits="AjaxWebApplication.AjaxPartialPageUpdate" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>

<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>

<asp:Button ID="Button1" runat="server" Text="Button" /></div>
</form>
</body>
</html>

After running the application we can see the output as following.

output without ajax

When we click on the button here a full page postback is occurred even we do not add click event handler yet. That page postback is happened default. However we add some code into Page_Load() event to print the time of day in those three labels.

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

namespace AjaxWebApplication
{
    public partial class AjaxPartialPageUpdate : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Label1.Text = DateTime.Now.TimeOfDay.ToString();
            Label2.Text = DateTime.Now.TimeOfDay.ToString();
            Label3.Text = DateTime.Now.TimeOfDay.ToString();
        }
    }
}

Output of the web page is as following.

output with time

When the button is clicked, the whole page is submitted. Therefore texts of three labels are updated as following.

output with time after postback

Until now there is nothing related with AJAX. Therefore we can add ScriptManager server control into the WebForm.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AjaxPartialPageUpdate.aspx.cs" Inherits="AjaxWebApplication.AjaxPartialPageUpdate" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>

<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>

<asp:Button ID="Button1" runat="server" Text="Button" /></div>
</form>
</body>
</html>

If that ScriptManager is added outside of the form tag, there is a runtime error like bellow.

scriptmanager error

Therefore we need to add the ScriptManager into the form tag like below. Then we can run the application without any error. The important thing that we want to state here is that a WebForm can have one and only one ScriptManager server control. Now we add another server control called UpdatePanel. Before adding anything into UpdatePanel we need to add ContentTemplate tag into it.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AjaxPartialPageUpdate.aspx.cs" Inherits="AjaxWebApplication.AjaxPartialPageUpdate" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>

<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>

<asp:Button ID="Button1" runat="server" Text="Button" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

</ContentTemplate>
</asp:UpdatePanel></div>
</form>
</body>
</html>

Because of the button is outside of the UpdatePanel still we can have the full page postback, then all three labels show a same time.

output with updatepanel

To apply the partial page update for the Label1 after button click that Label1 and the Button1 should be in the same UpdatePanel. Now we do not see any flickering in the browser window when the button is clicked.

output with updatepanel1

We can have multiple UpdatePanels in a one WebForm. Now we add another UpdatePanel like bellow.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AjaxPartialPageUpdate.aspx.cs" Inherits="AjaxWebApplication.AjaxPartialPageUpdate" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div>
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

<asp:Button ID="Button1" runat="server" Text="Button" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>

</ContentTemplate>
</asp:UpdatePanel></div>
</form>
</body>
</html>

And Label2 is added into the second UpdatePanel. The output is as below.

output with mutiple updatepanels

Because of one UpdatePanel is affected with other, content within those two UpdatePanels are going to be changed simultaneously. This is the default behavior of UpdatePanel. To change this behavior we need to change the mode of UpdatePanel, UpdateMode from default Always to Conditional.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AjaxPartialPageUpdate.aspx.cs" Inherits="AjaxWebApplication.AjaxPartialPageUpdate" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div>
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

<asp:Button ID="Button1" runat="server" Text="Button" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>

</ContentTemplate>
</asp:UpdatePanel></div>
</form>
</body>
</html>

Then we can update only the Label1 without affecting the Label2.

output with mutiple updatepanels1

If we add another button into the WebForm but outside any UpdatePanel, we again have a full page postback when the new button is clicked.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AjaxPartialPageUpdate.aspx.cs" Inherits="AjaxWebApplication.AjaxPartialPageUpdate" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div>
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

<asp:Button ID="Button1" runat="server" Text="Button" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>

</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="Button2" runat="server" Text="Button" /></div>
</form>
</body>
</html>

second button

We can wire up the second UpdatePanel with the second button using a trigger. But to update Label1 and Label2 separately we need to set UpdateMode in each UpdatePanel as Conditional.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AjaxPartialPageUpdate.aspx.cs" Inherits="AjaxWebApplication.AjaxPartialPageUpdate" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div>
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>

<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

<asp:Button ID="Button1" runat="server" Text="Button" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button2" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>

</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="Button2" runat="server" Text="Button" /></div>
</form>
</body>
</html>

Now we add AJAX Timer control into the WebForm but outside any UpdatePanel. We set interval of the Timer as 1000ms.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AjaxPartialPageUpdate.aspx.cs" Inherits="AjaxWebApplication.AjaxPartialPageUpdate" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div>
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>

<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

<asp:Button ID="Button1" runat="server" Text="Button" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button2" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>

</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="Button2" runat="server" Text="Button" />
<asp:Timer ID="Timer1" runat="server" Interval="1000"></asp:Timer></div>
</form>
</body>
</html>

We can see a full page postback after each 1 second. To limit this full page postback we can add another UpdatePanel and this Timer and Label3 should add into that UpdatePanel. Then we can see the update only for Label3.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AjaxPartialPageUpdate.aspx.cs" Inherits="AjaxWebApplication.AjaxPartialPageUpdate" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

<asp:Button ID="Button1" runat="server" Text="Button" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button2" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>

</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="Button2" runat="server" Text="Button" />
<asp:UpdatePanel ID="UpdatePanel3" runat="server">
<ContentTemplate>
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>

<asp:Timer ID="Timer1" runat="server" Interval="1000"></asp:Timer>
</ContentTemplate>
</asp:UpdatePanel></div>
</form>
</body>
</html>

Now we add a fourth UpdatePanel and another label and a button into that UpdatePanel. An UpdateProgress server control is added to the WebForm but outside any UpdatePanel. We associate UpdatePanel4 with UpdateProgress using AssociatedUpdatePanelID attribute.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AjaxPartialPageUpdate.aspx.cs" Inherits="AjaxWebApplication.AjaxPartialPageUpdate" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

<asp:Button ID="Button1" runat="server" Text="Button" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button2" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>

</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="Button2" runat="server" Text="Button" />
<asp:UpdatePanel ID="UpdatePanel3" runat="server">
<ContentTemplate>
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>

<asp:Timer ID="Timer1" runat="server" Interval="1000"></asp:Timer>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel4" runat="server">
<ContentTemplate>
<asp:Label ID="Label4" runat="server" Text="Label"></asp:Label>

<asp:Button ID="Button3" runat="server" Text="Button" OnClick="Button3_Click" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel4">
<ProgressTemplate>
An update is in progress...
</ProgressTemplate>
</asp:UpdateProgress></div>
</form>
</body>
</html>

We add 5 second delay artificially using threading and add the current time to the text of the Label4 in the click event in Button3.

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

namespace AjaxWebApplication
{
public partial class AjaxPartialPageUpdate : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = DateTime.Now.TimeOfDay.ToString();
Label2.Text = DateTime.Now.TimeOfDay.ToString();
Label3.Text = DateTime.Now.TimeOfDay.ToString();
}

protected void Button3_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(5000);
Label4.Text = DateTime.Now.TimeOfDay.ToString();
}
}
}

After that when we click the Button3, Label3 and Label4 freeze. UpdateProgress control print the string “An update is in progress…”.

updateprogress

After 5 second both Label3 and Label4 print the current time as below.

updateprogress1

This is a sample implementation with ASP.NET AJAX. You can use this demonstration to build different applications. You can download the source code from GitHub using https://github.com/hasiabewardana/ExperimentalAjaxWebApplication link. You will have awesome posts of useful programming areas soon. Stay tuned with us.

ASP.NET AJAX Introduction

AJAX is not a new programming language, but a new way to use existing standards. AJAX is the art of exchanging data with a server, and update parts of a web page – without reloading the whole page. There are too many web applications running on the web that are using AJAX technology such as gmailfacebook, twitter, google mapyoutube etc. Here we are going to discuss how ASP.NET uses AJAX under following topics.

  • ASP.NET AJAX Concepts
  • ASP.NET AJAX Architecture
  • Creating ASP.NET AJAX Application

AJAX Concepts

AJAX is an acronym for Asynchronous JavaScript and XML. This acronym was first coined by Jesse James Garrett in February 2005. The key idea behind the scene is that when a web form is normally submitted to the web server it is a synchronous full page submit. Then the user of the page can see visual feedback for that page submit and it may be an annoying thing. Instead a certain area of the web page is going to submit asynchronously and independently to the server. It is very efficient way to submit as well as get data to and from the server. This can be done through JavaScript in a manner that the Document Object Model (DOM) of the web page is accessed by JavaScript and insert data dynamically. The data exchange method of AJAX is XML. JavaScript written in AJAX is much complicated and we do not want to worry about because ASP.NET server controls are playing the major role. One most important feature from AJAX is Partial Page Updates. We can have submission of data dynamically and interactively while using the web page. Then we can see how web pages are more responsive. One other thing about AJAX is all based on open standards and cross platform. AJAX is not a Microsoft invention or acronym, it is a way of designing web pages. Different vendors have their own AJAX libraries. Microsoft presents ASP.NET AJAX as their library. This ASP.NET AJAX supports for data integration with web services, cross browser, rich user interface, integration with ASP.NET security and browser responsiveness.

ASP.NET AJAX Architecture

asp.net ajax architecture

Creating ASP.NET AJAX Application

We need ASP.NET AJAX Extensions and ASP.NET AJAX Server Controls in the Toolbox to create an AJAX enabled application.

ASP.NET AJAX Server Controls

ScriptManager

We can have one and only one ScriptManager in our web form. It manages all the scripts that are to be sent to the client. But the ScriptManager does not generate all the JavaScript that necessary. It is responsible for managing scripts that are produced by other server controls of the page.

UpdatePanel

Next most important server control is UpdatePanet and it enables the page for partial page updates. It has several properties. If we want to update a portion of a page then we need to add those portions of the page into own UpdatePanel.

UpdateProgress

This server control provides visual feedback about the progress that the partial page update is undergoing. Sometimes we need to keep waiting the user until some portion of the page is updated. For that thing UpdateProgress can be used.

Timer

This server control is used for periodic page postbacks which may be full or partial. If the timer is placed outside of an UpdatePanel a full page postback is occurred but the timer is in the UpdatePanel partial page postback is occurred. We can specify the time period in between two consecutive page updates.

You can see the implementation details of an ASP.NET AJAX enabled web application as the next post. Therefore stay tuned with us.