Walkthrough: Using Validation Controls Inside an UpdatePanel Control

In this walkthrough you will use validation controls inside an UpdatePanel control to perform validation in the browser.

The example is a simplified ticket query system. Users can specify a date and the number of tickets they want. When they submit the page, the page indicates whether tickets are available.

The controls that take user input are inside an UpdatePanel control. To make sure that users enter only valid values, you will also add validation controls inside the UpdatePanel control.

A button inside the UpdatePanel control performs an asynchronous postback, but only if user input is valid. When validation is successful in the browser, an asynchronous postback is performed and the panel's content is refreshed.

For more background about partial-page updates, see Partial-Page Rendering Overview.

Prerequisites

To implement the procedures in your own development environment you need:

  • Visual Studio 2008 or Visual Web Developer 2008 Express Edition.

  • An AJAX-enabled ASP.NET Web site.

Adding Input Controls in an UpdatePanel Control

To add input controls inside an UpdatePanel control

  1. In the ASP.NET Web site, create a new page and switch to Design view.

  2. If the page does not already contain a ScriptManager control, drag one from the AJAX Extensions tab of the Toolbox.

  3. From the AJAX Extensions tab of the Toolbox, drag an UpdatePanel control onto the page.

    UpdatePanel Tutorial

  4. From the Standard tab of the Toolbox, drag a TextBox, Calendar, TextBox, Button, and Label control inside the UpdatePanel control, in that order.

    Note

    Make sure that the controls are inside the UpdatePanel control.

  5. Type Select or enter a date: next to the first TextBox control.

  6. Type Select number of tickets (1-10): next to the second TextBox control.

  7. Select the Button control, and then set its Text property to Check Availability.

  8. Select the Label control and clear its Text property.

    The resulting page will resemble the following in Design view:

    UpdatePanel Tutorial

  9. Double-click the Calendar control to add an event handler for its SelectionChanged event.

  10. In the event handler, add the following code, which sets the text of the first TextBox to the selected date and clears the Label control's Text property.

    Protected Sub Calendar1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        TextBox1.Text = Calendar1.SelectedDate.ToShortDateString()
        Label1.Text = ""
    End Sub
    
    protected void Calendar1_SelectionChanged(object sender, EventArgs e)
    {
        TextBox1.Text = Calendar1.SelectedDate.ToShortDateString();
        Label1.Text = "";
    }
    
  11. Switch to Design view.

  12. Double-click the Button control to add an event handler for its Click event.

  13. In the event handler, add the following code, which sets the text of the Label control during an asynchronous postback.

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Label1.Text = "Tickets are available as of " & DateTime.Now.ToString() & "."
    End Sub
    
    protected void Button1_Click(object sender, EventArgs e)
    {
        Label1.Text = "Tickets are available as of " + DateTime.Now.ToString() + ".";
    }
    

    This event handler is where you would add custom code for your own ticket application.

  14. Save the changes and then press CTRL+F5 to view the page in a browser.

  15. Select a date, enter a number between 1 and 10, and then click Check Availability.

    The button causes an asynchronous postback that updates the Label control with ticket availability information.

    The following example shows the complete markup.

    <%@ Page Language="VB" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <script runat="server">
        Protected Sub Calendar1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs)
            TextBox1.Text = Calendar1.SelectedDate.ToShortDateString()
            Label1.Text = ""
        End Sub
        Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            Label1.Text = "Tickets are available as of " & DateTime.Now.ToString() & "."
        End Sub
    </script>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <title>UpdatePanel with Validators Example</title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:ScriptManager ID="ScriptManager1" runat="server" />
                <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                <ContentTemplate>
                    Select a date below or enter a date:
                    <asp:TextBox ID="TextBox1" runat="server" Width="70px"></asp:TextBox><br />
                    <asp:Calendar ID="Calendar1" runat="server" OnSelectionChanged="Calendar1_SelectionChanged" />
                    <br />
                    Specify number of tickets (1-10):
                    <asp:TextBox ID="TextBox2" runat="server" Width="40px"></asp:TextBox><br />
                    <asp:Button ID="Button1" runat="server" OnClientClick="ClearLastMessage('Label1')" Text="Check Availability" OnClick="Button1_Click" />
                    <br />
                    <br />
                    <asp:Label ID="Label1" runat="server"></asp:Label>
                    <br />
                </ContentTemplate>
                </asp:UpdatePanel>
            </div>
        </form>
    </body>
    </html>
    
    <%@ Page Language="C#" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <script runat="server">
    
        protected void Calendar1_SelectionChanged(object sender, EventArgs e)
        {
            TextBox1.Text = Calendar1.SelectedDate.ToShortDateString();
            Label1.Text = "";
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            Label1.Text = "Tickets are available as of " + DateTime.Now.ToString() + ".";
        }
    
    </script>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <title>UpdatePanel with Validators Example</title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:ScriptManager ID="ScriptManager1" runat="server" />
                <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                <ContentTemplate>
                    Select a date below or enter a date:
                    <asp:TextBox ID="TextBox1" runat="server" Width="70px"></asp:TextBox><br />
                    <asp:Calendar ID="Calendar1" runat="server" OnSelectionChanged="Calendar1_SelectionChanged" />
                    <br />
                    Specify number of tickets (1-10):
                    <asp:TextBox ID="TextBox2" runat="server" Width="40px"></asp:TextBox><br />
                    <asp:Button ID="Button1" runat="server" OnClientClick="ClearLastMessage('Label1')" Text="Check Availability" OnClick="Button1_Click" />
                    <br />
                    <br />
                    <asp:Label ID="Label1" runat="server"></asp:Label>
                    <br />
                </ContentTemplate>
                </asp:UpdatePanel>
            </div>
        </form>
    </body>
    </html>
    

Adding Validation for the Input Controls

At this point, user input into the page is not validated. Users can enter nothing, or a date in the past, or a number outside the range of 1 to 10. Therefore, you will now add validation controls inside the UpdatePanel control to guard against these scenarios.

The following procedure adds client validation so that the text box controls inside the panel must be filled in and with values in the correct range. A validation summary control is used to display validation error messages. The page will perform an asynchronous postback only if the validation is successful.

To add validation to input controls inside an UpdatePanel

  1. In the page you created earlier, switch to Design view.

  2. From the Validation tab of the Toolbox, drag a CompareValidator and a RequiredFieldValidator control to the UpdatePanel control.

    For the CompareValidator control, set the properties as follows:

    Property

    Setting

    ControlToValidate

    TextBox1

    ErrorMessage

    Pick a date in the future.

    Operator

    GreaterThanEqual

    Type

    Date

    Display

    None

    For the RequiredFieldValidator control, set the properties as follows:

    Property

    Setting

    ControlToValidate

    TextBox1

    ErrorMessage

    Date is required.

    These two validation controls validate user input in the first TextBox control. The validation controls make sure that users enter a value and that the value represents a date in the future. The ValueToCompare property of the CompareValidator will be added programmatically in a later step.

    The Display property for the validation controls is set to None. Later you will add a ValidationSummary control to display all validation errors in one location.

  3. From the Validation tab of the Toolbox, drag a RangeValidator and a RequiredFieldValidator control to the UpdatePanel control.

    For the RangeValidator control, set the properties as follows:

    Property

    Setting

    ControlToValidate

    TextBox2

    ErrorMessage

    Number of tickets out of range.

    MinimumValue

    1

    MaximumValue

    10

    For the RequiredFieldValidator control, set the properties as follows:

    Property

    Setting

    ControlToValidate

    TextBox2

    ErrorMessage

    Number of tickets is required.

    These validation controls validate user input in the second TextBox control. The controls make sure that users enter a value and that it is in the range of 1 to 10.

  4. From the Validation tab of the Toolbox, drag a ValidationSummary control to the UpdatePanel control.

    The resulting page in Design view will resemble the following figure.

    UpdatePanel Tutorial

  5. Double-click anywhere in the page outside the UpdatePanel control to add a handler for the page load event.

  6. Add the following code to the handler.

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
        CompareValidator1.ValueToCompare = DateTime.Now.ToShortDateString()
    End Sub
    
    protected void Page_Load(object sender, EventArgs e)
    {
        CompareValidator1.ValueToCompare = DateTime.Now.ToShortDateString();
    }
    

    This code sets the ValueToCompare property of the CompareValidator control to today's date.

  7. Switch to Source view.

  8. Add the following client script just after the markup for the ScriptManager control.

    <script type="text/javascript">
    function ClearLastMessage(elem)
    {
       $get(elem).innerHTML = '';
    }
    </script>
    
    <script type="text/javascript">
    function ClearLastMessage(elem)
    {
       $get(elem).innerHTML = '';
    }
    </script>
    

    The code clears the status message hat is returned from the last successful query.

  9. Switch to Design View

  10. Select the Button control and set the OnClientClick property to ClearLastMessage('Label1').

    This causes the button to call the script function ClearLastMessage (which you defined previously) and pass it the name of the element to clear.

  11. Save the changes and then press CTRL+F5 to view the page in a browser.

  12. Select a date in the past and then click Check Availability.

    The validation summary control displays a message, and no asynchronous postback occurs.

  13. Select a date in the future, specify a number of tickets between 1 and 10, and then click Check Availability.

    This time validation succeeds and the asynchronous postback occurs.

    The following example shows the complete code.

    <%@ Page Language="VB" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <script runat="server">
    
        Protected Sub Calendar1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs)
            TextBox1.Text = Calendar1.SelectedDate.ToShortDateString()
            Label1.Text = ""
        End Sub
        Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            Label1.Text = "Tickets are available as of " & DateTime.Now.ToString() & "."
        End Sub
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
            CompareValidator1.ValueToCompare = DateTime.Now.ToShortDateString()
        End Sub
    
    </script>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <title>UpdatePanel with Validators Example</title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:ScriptManager ID="ScriptManager1" runat="server" />
                <script type="text/javascript">
                function ClearLastMessage(elem)
                {
                   $get(elem).innerHTML = '';
                }
                </script>
                <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                <ContentTemplate>
                    Select a date below or enter a date:
                    <asp:TextBox ID="TextBox1" runat="server" Width="70px"></asp:TextBox><br />
                    <asp:Calendar ID="Calendar1" runat="server" OnSelectionChanged="Calendar1_SelectionChanged" />
                    <br />
                    Specify number of tickets (1-10):
                    <asp:TextBox ID="TextBox2" runat="server" Width="40px"></asp:TextBox><br />
                    <asp:Button ID="Button1" runat="server" OnClientClick="ClearLastMessage('Label1')" Text="Check Availability" OnClick="Button1_Click" />
                    <br />
                    <br />
                    <asp:Label ID="Label1" runat="server"></asp:Label>
                    <br />
                    <asp:CompareValidator ID="CompareValidator1" runat="server" ControlToValidate="TextBox1"
                        ErrorMessage="Pick a date in the future." Operator="GreaterThanEqual" Type="Date" Display="None">
                    </asp:CompareValidator>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1"
                        ErrorMessage="Date is required." Display="None">
                    </asp:RequiredFieldValidator>
                    <asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="TextBox2"
                        ErrorMessage="Number of tickets out of range." MaximumValue="10"
                        MinimumValue="1" Type="Integer" Display="None">
                    </asp:RangeValidator>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TextBox2"
                         ErrorMessage="Number of tickets is required." Display="None">
                    </asp:RequiredFieldValidator>
                    <asp:ValidationSummary ID="ValidationSummary1" runat="server" />
                </ContentTemplate>
                </asp:UpdatePanel>
            </div>
        </form>
    </body>
    </html>
    
    <%@ Page Language="C#" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <script runat="server">
    
        protected void Calendar1_SelectionChanged(object sender, EventArgs e)
        {
            TextBox1.Text = Calendar1.SelectedDate.ToShortDateString();
            Label1.Text = "";
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            Label1.Text = "Tickets are available as of " + DateTime.Now.ToString() + ".";
        }
    
        protected void Page_Load(object sender, EventArgs e)
        {
            CompareValidator1.ValueToCompare = DateTime.Now.ToShortDateString();
        }
    
    </script>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <title>UpdatePanel with Validators Example</title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:ScriptManager ID="ScriptManager1" runat="server" />
                <script type="text/javascript">
                function ClearLastMessage(elem)
                {
                   $get(elem).innerHTML = '';
                }
                </script>
                <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                <ContentTemplate>
                    Select a date below or enter a date:
                    <asp:TextBox ID="TextBox1" runat="server" Width="70px"></asp:TextBox><br />
                    <asp:Calendar ID="Calendar1" runat="server" OnSelectionChanged="Calendar1_SelectionChanged" />
                    <br />
                    Specify number of tickets (1-10):
                    <asp:TextBox ID="TextBox2" runat="server" Width="40px"></asp:TextBox><br />
                    <asp:Button ID="Button1" runat="server" OnClientClick="ClearLastMessage('Label1')" Text="Check Availability" OnClick="Button1_Click" />
                    <br />
                    <br />
                    <asp:Label ID="Label1" runat="server"></asp:Label>
                    <br />
                    <asp:CompareValidator ID="CompareValidator1" runat="server" ControlToValidate="TextBox1"
                        ErrorMessage="Pick a date in the future." Operator="GreaterThanEqual" Type="Date" Display="None">
                    </asp:CompareValidator>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1"
                        ErrorMessage="Date is required." Display="None">
                    </asp:RequiredFieldValidator>
                    <asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="TextBox2"
                        ErrorMessage="Number of tickets out of range." MaximumValue="10"
                        MinimumValue="1" Type="Integer" Display="None">
                    </asp:RangeValidator>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TextBox2"
                         ErrorMessage="Number of tickets is required." Display="None">
                    </asp:RequiredFieldValidator>
                    <asp:ValidationSummary ID="ValidationSummary1" runat="server" />
                </ContentTemplate>
                </asp:UpdatePanel>
            </div>
        </form>
    </body>
    </html>
    

Review

This walkthrough demonstrated how to use validators inside UpdatePanel controls. It is recommended that you put validation controls (including validation summary controls) inside the same panel as the input controls that they validate.

See Also

Concepts

Types of Validation for ASP.NET Server Controls

Partial-Page Rendering Overview

UpdatePanel Control Overview

Reference

Validating User Input in ASP.NET Web Pages