Introduction To Asp .Net Ajax 4 (Timer)

Timer is a Asp .Net Ajax Control to do a repetitive task. It is similar with Windows Form Timer Control or in Javascript point of view is windows.setInterval method.

Timer Event is Tick. It has interval properties in miliseconds. Interval is a time between tick event triggers itself. So this tick event runs on specific interval of time.

If you want to have a repeated automatic refresh to view current information or action like auto save then you can use Timer Control.
Since it is an ajax process then page will reload partially or process will run asynchronously.

Example

I have a Timer Example just to view clock in a panel. Every second, clock in panel will be refreshed and show current hour, minute and second.
The source code I give you is a block code because other lines are auto-generated by Visual Studio. Here is an .aspx block code:

<form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="updatepanel1" runat="server" >
            <ContentTemplate>
                <asp:Panel ID="panel1" runat="server" BorderColor="Blue" BackColor="Lime">
                    <asp:Label ID="label1" runat="server"></asp:Label>
                </asp:Panel>
                 <asp:Timer ID="timer1" runat="server" Interval="1000"></asp:Timer>
            </ContentTemplate>
           
        </asp:UpdatePanel>
       
    </div>
    </form>

I drag and drop ScriptManager to enable Asp .Net Ajax and UpdatePanel as a container of controls that will be processed asynchronously.
So when ajax process is triggered only controls inside UpdatePanel and ContentTemplate will be reloaded not the whole page and I set Timer interval to 1000 milisecond.
This will make Tick event triggered every second.

Code behind file (.vb):

Protected Sub timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles timer1.Tick
        label1.Text = DateTime.Now.ToLongTimeString()
    End Sub

This timer control simplifies us in writing code. We dont need to write a Javascript window.setInterval method, PageMethods and its callbacks to make a repeatitive task.

This timer control can be writen outside the UpdatePanel but we have to use Triggers and AsyncPostBackTrigger Tag inside UpdatePanel.

<form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>

        <asp:UpdatePanel ID="updatepanel1" runat="server" >
            <ContentTemplate>
                <asp:Panel ID="panel1" runat="server" BorderColor="Blue" BackColor="Lime">
                    <asp:Label ID="label1" runat="server"></asp:Label>
                </asp:Panel>
               
            </ContentTemplate>
           <Triggers>
            <asp:AsyncPostBackTrigger ControlID="timer1" EventName="Tick" />
           </Triggers>
        </asp:UpdatePanel>
        <asp:Timer ID="timer1" runat="server" Interval="1000"></asp:Timer>
    </div>
    </form>

Above code will produce the same result.

Auto Save Example

Here I give example to save miscelanous draft automatically every interval of time by Timer event. This auto save can be used on messaging, blog post, documents etc.
You can set the interval time to any value that reasonable.

For demonstration purposes I only store a draft’s text on a Session variable. So I can set the time interval to several seconds only.
In a real world, you might need to save draft on database. So time interval must be good estimated regarding to server resources.

In this example, if draft is automatically saved then ‘Draft automatically saved’ message appear on a label control. I also have two buttons which are ‘Save’
to save a draft by user action and ‘Showed Saved Draft’ to show saved draft either by timer event or user action to a Literal control.

See below snapshot

The source code I give you is a block code because other lines are auto-generated by Visual Studio. Here is an .aspx block code:

<form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <asp:Panel ID="panel1" runat="server" Width="250" BackColor="Azure" Visible="false">
                <asp:Label ID="label1" runat="server" Font-Underline="true"></asp:Label>
            </asp:Panel>
            
        </ContentTemplate>
         <Triggers>
                <asp:AsyncPostBackTrigger ControlID="timer1" EventName="Tick" />
            </Triggers>
        </asp:UpdatePanel>
		
        <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
        <table>
            <tr valign="top">
            <td>             
            Write a Draft:<br />
            <asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" Width="250" Height="210"></asp:TextBox><br />
            <asp:Button ID="btnSave" runat="server" Text="Save" /> &nbsp;<asp:Button ID="btnShowSaved" runat="server" Text="Show Saved Draft" /></td>
            <td>
            <asp:Literal ID="literal1" runat="server"></asp:Literal>
            </td>
            </tr>
            </table>      
        </ContentTemplate>
        </asp:UpdatePanel>
        
        <asp:Timer ID="timer1" runat="server" Interval="6000" ></asp:Timer>
    </div>
    </form>

I have two updatepanel controls so changes in one updatepanel will not affecting controls in other updatepanel with help of ‘UpdateMode’ properties.

There are two types of UpdateMode which are Always and Conditional. The default is Always. Every async postback from updatepanel1 will always get updatepanel2 affected and so the other way around.

Conditional UpdateMode makes async update of UpdatePanel independent from other UpdatePanel. It makes the repeat Auto Save process not disturbing your draft writing.

Code behind file (.vb):

Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
	Session("draft") = Textbox1.Text
	label1.Text = "Draft saved on " & DateTime.Now.ToLongTimeString()
	panel1.Visible = True
End Sub

Protected Sub timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles timer1.Tick
	If TextBox1.Text <> "" Then
		Session("draft") = TextBox1.Text
		label1.Text = "Draft automatically saved on " & DateTime.Now.ToLongTimeString()
		panel1.Visible = True
	End If
End Sub

Protected Sub btnShowSaved_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnShowSaved.Click
	literal1.Text = "Draft preview: <br> " & Session("draft").ToString().Replace(Chr(13), "<br>")
End Sub

Related articles:

  1. Introduction To Asp .Net Ajax (ScriptManager, UpdatePanel, ContentTemplate, Triggers)
  2. Introduction to Asp .Net Ajax – 2 (UpdateProgress)
  3. Introduction To Asp .Net Ajax Client Side Development ($get, $addhandler, $removehandler, Sys.Application, Sys.WebForms, Sys.Net)
  4. Introduction To Asp .Net Ajax 3 (ScriptManagerProxy)

Regards,
Agung Gugiaji

Advertisements

5 responses to “Introduction To Asp .Net Ajax 4 (Timer)

  1. Pingback: Building Web Chat From Scratch Using Asp .Net Ajax Timer | Enlighten Application Developer Journals

  2. Hey there would you mind letting me know
    which hosting company you’re

    working with? I’ve loaded your blog in 3 different web

    browsers and I must say this blog loads a lot faster then most.
    Can you suggest a good

    web hosting provider at a honest price? Cheers,
    I appreciate it!

  3. I was curious if you ever thought of changing the layout
    of your blog? Its very well written; I love what youve
    got to say. But maybe you could a little more in
    the way of content so people could connect with it better.
    Youve got an awful lot of text for only having one or 2 images.

    Maybe you could space it out better?

  4. I’ve been exploring for a little for any high-quality articles or blog posts on this sort of space . Exploring in Yahoo I at last stumbled upon this website. Reading this info So i’m satisfied to convey that I have a very excellent uncanny feeling I came upon exactly what I needed.
    I so much definitely will make sure to don?t disregard this site and
    give it a look regularly.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s