When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles
ASPFAQs.com
Message Board
Related Web Technologies
User Tips!
Coding Tips
Search

Sections:
Book Reviews
Sample Chapters
Commonly Asked Message Board Questions
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Security
Stump the SQL Guru!
Web Hosts
XML
Information:
Advertise
Feedback
Author an Article

ASP ASP.NET ASP FAQs Message Board Feedback
 
Print this Page!
Published: Wednesday, August 6, 2008

Displaying a Message in Response to Some Action and Then Hiding It on Subsequent Postbacks

By Scott Mitchell


Introduction


ASP.NET web pages commonly display messages in response to user actions. For instance, a typical CRUD (Create, Read, Update, Delete) web page might display the message, "Record deleted" immediately after deleting a record and the message "Record updated" immediately after updating a record. Likewise, there would be messages displayed for inserting a new record and messages displayed in the event of an error. Such messages are typically displayed using a single Label Web control. This control may be located at the top of the page and have its Text property initially set to empty string. Then, when particular events transpire, the Label's Text property is updated accordingly.

The problem with this approach is that the Label's Text property value is remembered across postbacks. Consequently, if a user deletes a record the "Record deleted" message is displayed. If the user next sorts or pages the CRUD grid or perform some other action that results in a postback, the Label control continues to display the message "Record deleted," which is now outdated. What we want is to have the Label's Text property revert to an empty string on subsequent postbacks.

There are two simple and straightforward techniques at our disposal for implementing such functionality. This article examines these two approaches and includes a working demo available for download that highlights both approaches. Read on to learn more!

- continued -

The Problem With the Label's Default Behavior


The download available at the end of this article includes a CRUD-like web page that displays records from the Northwind database's Products table in a GridView. From the GridView the user can page, sort, edit, and delete products. On this page we would like to display a message when certain events transpire. For example, whenever a user updates a record we want to display the message "The product ProductName has been updated." A similar message should be displayed when the user deletes a product. Additionally, if there is a problem with the user's input when updating a product a message should be displayed. In particular, this demo's business rules and require that when updating a product the new product price cannot be more than twice the old price. If the new price exceeds these bounds then the message "You cannot change a product's price to more than twice what it was before" is displayed.

This functionality can be implemented using a Label Web control and setting the Label's Text property to the appropriate message to display. Specifically, the Label's Text property is assigned during appropriate event handlers. For instance, to display a message when a product has been updated we can create an event handler for the GridView's RowUpdated event. The RowUpdated event fires after the product has been updated in the database and includes information on the updated values.

protected void Products_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
   LabelID.Text = string.Format("The product {0} has been updated.", e.NewValues["ProductName"]);
}

The problem with this approach is that the Label remembers the value of its Text property across postbacks. That means that after a message is displayed in the Label control it remains displayed until the user performs another action that causes the message to be overwritten. The following screenshots show this shortcoming in action. The first screenshot shows the page immediately after the product Chang has been updated. Note the message at the top of the page, "The product Chang has been updated."

A message is displayed when a product is updated.

This message remains on the screen until the user updates or deletes another product. The message remains as the user pages or sorts the grid. The following screenshot illustrates this undesirable behavior. At this point, the grid has been sorted and paged a number of times, yet the "The product Chang has been updated" message remains at the top of the screen.

The message remains displayed even though the grid has been sorted and paged a number of times.

Another concern is that any formatting changes to the Label are also remembered across postbacks. For example, if the user attempts to update a product's price to a value that is more than twice its original value the code displays the message "You cannot change a product's price to more than twice what it was before" in a red font. This change of the Label's ForeColor property to Red is remembered across postbacks. Therefore, unless it is explicitly set back to Black subsequent messages will be displayed in a red font.

The following screenshots illustrate this behavior. In the first screenshot, the user has attempted to update the Aniseed Syrup product's price to a value more than twice the original value ($10.00). The corresponding message is displayed in a red font.

The message is displayed in a red font.

This red color remains because the Label's ForeColor property is not explicitly reset to Black in the other event handlers. The net result is that the other messages that are displayed when a user updates or deletes a product are now displayed in red, as well. The following screenshot shows the message after Aniseed Syrup has been updated with an appropriate price value. Note how the message "The product Aniseed Syrup has been updated" is displayed in a red font.

The update message is now displayed in a red font, as well.

The good news is that it is easy to configure the page such that the message is only displayed on the postback immediately following the event of interest and that its formatting properties or appropriately reset. The remainder of this article examines to such techniques.

Technique #1: Resetting the Label's Text Property on Every Page Load


Every time an ASP.NET page is requested - be it the first visit to the page or subsequent postbacks - the Page_Load event handler executes. What's more, the Page_Load event handler always executes before the event handlers for the Web controls on the page. Because we are assigning the Label's Text property in the GridView's event handlers, we can use the Page_Load event handler to reset the Label's Text property (and any of the Label's other properties that are assigned in the GridView's event handlers) on every visit to the page.

protected void Page_Load(object sender, EventArgs e)
{
   LabelID.Text = string.Empty;
   LabelID.ForeColor = Color.Empty;
}

Whenever the page is visited the above code resets the Label Web control to its initial state. On the first visit to the page the Label displays nothing, which is the desired behavior. When the user deletes a product, for example, a postback occurs and the Page_Load event handler executes, resetting the Label Web control. Following that, the product is deleted and the GridView's RowDeleted event handler executes, setting the Label's Text property to the appropriate message, thereby displaying it in the user's browser. If the user then sorts or pages through the grid a postback ensues and the Page_Load event handler executes, resetting the Label Web control. Consequently, on the subsequent postback the product deleted message is no longer displayed!

Note: In addition to resetting the ForeColor property here you should also reset any other formatting properties that are assigned to the Label Web control from any event handlers.

Technique #2: Disable the Label's EnableViewState Property


Keep in mind that the problem we are facing is that the Label Web control remembers the programmatic changes to its properties across postbacks. One way to fix this is to programmatically reset the Label Web control on each visit to the page, which is what Technique #1 did. Another option is to simply disable the functionality that allows the Label to remember changes to its properties. ASP.NET uses view state to remember programmatic changes to Web control's properties across postbacks.

The good news is that we can disable view state on a control-by-control basis. That is, we can instruct the Label Web control to not use view state. The net effect is that any programmatic changes to the Label's properties will not be remembered to the next postback. This means that the Label will revert to its initial state on every postback, which is what we wrote code to do in Technique #1.

To used this technique simply set the Label's EnableViewState property to False in the declarative syntax; also, clear out its Text property.

<asp:Label ID="LabelID" runat="server" EnableViewState="False" />

That's all there is to it! By simply setting the EnableViewState property to False any programmatic changes to the Label's properties are "forgotten" on the subsequent postback. The benefit of this technique is that it requires no code - just set a property in the declarative syntax and you're off and running.

Trying Out The Techniques


The demo available for download at the end of this article includes a single CRUD-like page with three Label controls:
  • MessageWithDefaultBehavior - exhibits the default, view state enabled behavior.
  • MessageWithViewState - has view state enabled, but has its properties reset in the Page_Load event handler.
  • MessageViewStateDisabled - exhibits the behavior when the EnableViewState property is set to False.
As you will see, the MessageWithViewState and MessageViewStateDisabled Labels produce the same output, namely they only show up immediately after the event that triggered their display and then disappear on subsequent postbacks. The MessageWithDefaultBehavior Label, however, remains displayed on subsequent postbacks.

Many ASP.net pages require that messages be displayed in response to particular user actions. Oftentimes, these messages need to disappear on subsequent postbacks. By default, the Label Web control remembers programmatic changes to its properties, which causes your messages to remain displayed on subsequent, unrelated postbacks. There are, however, workarounds, and now that you read this article you know how to apply two of them.

Happy Programming!

  • By Scott Mitchell


    Attachments


  • Download the code used in this article

    Further Reading


  • The ASP.NET View State
  • Understanding ASP.NET View State


  • ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article