To read the article online, visit http://www.4GuysFromRolla.com/articles/111506-1.aspx

Client-Side Enhancements in ASP.NET 2.0

By Scott Mitchell


Introduction


ASP.NET's model of Web controls, server-side event handlers, and view state work in unison to help blur the lines between the client and the server. In short, a developer designing an ASP.NET web page can think in terms of higher-level abstrations - TextBoxes, Buttons, Click events, and so on - and not have to worry about the low-level details of HTML, JavaScript, and how data is shuttled from the web server down to the client's web browser, and back again. However, it is important to be aware of the distinction between the client and the server.

Oftentimes, the overall user experience can be enhanced by intelligently adding client-side script. By associating script with client-side user actions, it is possible to provide a snappier user interface or to enhance the overall experience. For example, when clicking a Delete button on a web form, rather than blindly deleting the record or posting back to a confirmation page, client-side script can be used to display a confirm messagebox, asking the user if they're certain they want to proceed with the delete. Clicking OK would proceed with the postback, while clicking Cancel would short circuit it.

A client-side confirm messagebox.

Adding such client-side functionality in ASP.NET version 1.x almost always involved writing code. And for more advanced scenarios, the amount of code - both server-side and client-side - could easily explode. ASP.NET 2.0 has added a number of enhancements that make performing common client-side tasks as easy as setting a property. In this article we will look at how to programmatically set focus to a Web control, how to add client-side script when a Button is clicked, and how to maintain scroll position on postbacks. Read on to learn more!

Setting Focus to a Web Control


All form fields in a web page have the ability to programmatically receive focus in the client's web browser via the using the JavaScript focus() method. For example, if the web page contains a textbox with a client-side id of myTextBox (such as <input type="text" id="myTextBox" />), the following JavaScript will set focus to the textbox:

var tb = document.getElementById('myTextBox');
if (tb != null)
   tb.focus();

This technique is commonly used to set focus to a particular form field when the page first loads. For example, when visiting Google's homepage, focus is set immediately to the search textbox, allowing visitors to immediately start entering they query without having to first click on the textbox with their mouse. (For more information on using JavaScript to set a form field's focus on page load, see the Focus On Load JavaScript demo at The JavaScript Source.)

To have a Web control receive focus on page load in ASP.NET 1.x, the page developer needed to inject the above JavaScript into the page. With ASP.NET 2.0, all Web controls have a Focus() method that can be invoked on the server-side. Doing so automatically injects the necessary JavaScript. For example, if we have an ASP.NET page with a TextBox Web control whose ID is SearchQuery, we could use the following Page_Load event handler to set focus to this control on page load:

protected void Page_Load(object sender, EventArgs e)
{
   // Set focus to the SearchQuery TextBox
   

SearchQuery.Focus();


}

Calling the Focus() method automatically injects the following script include into the rendered page:

<script src="/Directory/WebResource.axd?d=JA7BpX_wFudgXazbqxO5Dw2&t=632965002926288600" type="text/javascript"></script>

The WebResource.axd reference is a special path that returns a specific set of JavaScript functions to be used by the client. (See Accessing Embedded Resources through a URL using WebResource.axd for more information on how WebResource.axd is used to serve content.) One of the JavaScript files included is WebForm_AutoFocus(control), which has the following definition:

function WebForm_AutoFocus(focusId) {
  var targetControl;
  if (__nonMSDOMBrowser) {
    targetControl = document.getElementById(focusId);
  }
  else {
    targetControl = document.all[focusId];
  }
  var focused = targetControl;
  if (targetControl && (!WebForm_CanFocus(targetControl)) ) {
    focused = WebForm_FindFirstFocusableChild(targetControl);
  }
  if (focused) {
    try {
      focused.focus();
      if (__nonMSDOMBrowser) {
        focused.scrollIntoView(false);
      }
      if (window.__smartNav) {
        window.__smartNav.ae = focused.id;
      }
    }
    catch (e) {
    }
  }
}

In addition to adding the above script reference, calling the Focus() method also adds the following call to WebForm_AutoFocus(control) right before the closing </form> element:

WebForm_AutoFocus('SearchQuery');

In short, calling the Focus() method on the server-side automatically injects the appropriate script functions and a call to the WebForm_AutoFocus(control) function, meaning that we do not need to bother with crafting the JavaScript ourselves. The download available at the end of this article includes a live demo of the Focus() method along with the other techniques examined in this article.

Performing a Client-Side Action When a Button, LinkButton, or ImageButton is Clicked


When a Button, LinkButton, or ImageButton Web control is clicked, a postback ensues. Sometimes, though, rather than immediately performing a postback we'd first like to perform some client-side task. A common example is in displaying a confirm dialog box that prompts the end user whether they want to perform the action associated with the button being clicked. Regardless of what script you want executed when the button is clicked, you can specify it through the Button, LinkButton, or ImageButton's OnClientClick property.

The confirm dialog box can be displayed through the JavaScript confirm(msg) function. confirm(msg) displays a modal dialog box with an OK and Cancel button, displaying the text msg within the messagebox. If the end user clicks OK, confirm(msg) returns true; if Cancel is clicked, it returns false. When submitting a form, if one of the client-side event handlers returns false, the browser stops the form submission. Therefore, an end user can click the Cancel button to stop the postback and thereby prevent the server-side action from occurring.

To add a confirmation dialog box to a Button Web control, simply set its OnClientClick property to return confirm('msg');, like so:

<asp:Button ID="ConfirmOnClick" runat="server"
         

OnClientClick="return confirm('You\'re sure you want to do this?');"


         Text="Launch Airstrike" />

Since the msg value passed into the confirm(msg) function is delimited by apostrophes, if you have any apostrophes in msg they must be escaped using \', like in "You\'re" in the above example. Adding a value for the OnClientClick property results in rendered HTML that includes an onclick attribute, like:

<input type="submit" name="ConfirmOnClick" value="Launch Airstrike" onclick="return confirm('You\'re sure you want to do this?');" id="ConfirmOnClick" />

Adding such confirmation dialog boxes is quite possible in ASP.NET version 1.x, but requires writing code. See Adding Client-Side Message Boxes in Your ASP.NET Web Pages for more information on achieving this functionality with ASP.NET 1.x.

Maintaining Scroll Position on Postback


When working with large web pages where users typically have to scroll down, one annoyance that can occur when a Button, LinkButton, or ImageButton far down on the page is clicked is that, on postback, the browser returns to the top of the page. That is, if a user has to scroll down to click a button that causes a postback, on postback the browser will reload the document and be at the top of the page, meaning that the user has to scroll back down to where the button was clicked from if they want to see or work with the page at that point. This is a common pain when working with an editable GridView that may span many pages - when scrolling down and clicking the Edit button for some row that's not visible from the very top of the page, on postback the user has to scroll back down to the row being edited.

A previous 4Guys article authored by Steve Stchur - Maintaining Scroll Position on Postback - examined how to add a bit of JavaScript that would remember the X and Y scroll positions across postbacks and use JavaScript on the postback to "restore" the user's scroll position. I've personally used Steve's technique in a number of my ASP.NET 1.x projects over the past several years.

ASP.NET 2.0 makes remembering scroll position on postback even easier, as the ASP.NET 2.0 engine will kindly inject the necessary JavaScript and HTML elements necessary to remember scroll position across postbacks. To turn on this feature in ASP.NET 2.0, simply set the MaintainScrollPositionOnPostback directive to True, either on the page-level or in Web.config if you want it to apply to all pages in the website. To apply it for a single page, just update the <% @Page %gt; directive so that it looks lkike:

<%@ Page Language="..." MaintainScrollPositionOnPostback="true" ... %>

To apply this setting to all pages in the website, add the following markup to the Web.config file (within the <system.web> element):

<pages maintainScrollPositionOnPostBack="true" />

Turning on the MaintainScrollPositionOnPostback feature adds two hidden form fields to the rendered markup to track the X and Y scroll positions across postbacks:

<input type="hidden" name="__SCROLLPOSITIONX" id="__SCROLLPOSITIONX" value="0" />
<input type="hidden" name="__SCROLLPOSITIONY" id="__SCROLLPOSITIONY" value="0" />

Also, script is injected to associate the web form's client-side onsubmit event handler with the WebForm_SaveScrollPositionOnSubmit() function, which saves the current scroll positions in the hidden form fields shown above. On postback, the window's client-side onload event handler is configured to call the WebForm_RestoreScrollPosition() function, which restores the scroll position prior to the postback. Both the WebForm_SaveScrollPositionOnSubmit() and WebForm_RestoreScrollPosition() functions are included in the page via a JavaScript include to WebResource.axd?d=KJ8KmyYEIkBWV17-XIEtOQ2, which defines these functions as such:

function WebForm_GetScrollX() {
  if (__nonMSDOMBrowser) {
    return window.pageXOffset;
  }
  else {
    if (document.documentElement && document.documentElement.scrollLeft) {
      return document.documentElement.scrollLeft;
    }
    else if (document.body) {
      return document.body.scrollLeft;
    }
  }
  return 0;
}

function WebForm_GetScrollY() {
  if (__nonMSDOMBrowser) {
    return window.pageYOffset;
  }
  else {
    if (document.documentElement && document.documentElement.scrollTop) {
      return document.documentElement.scrollTop;
    }
    else if (document.body) {
      return document.body.scrollTop;
    }
  }
  return 0;
}

function WebForm_SaveScrollPositionOnSubmit() {
  theForm.__SCROLLPOSITIONX.value = WebForm_GetScrollX();
  theForm.__SCROLLPOSITIONY.value = WebForm_GetScrollY();
  if ((typeof(this.oldOnSubmit) != "undefined") && (this.oldOnSubmit != null)) {
    return this.oldOnSubmit();
  }
  return true;
}

function WebForm_RestoreScrollPosition() {
  if (__nonMSDOMBrowser) {
    window.scrollTo(theForm.elements['__SCROLLPOSITIONX'].value, theForm.elements['__SCROLLPOSITIONY'].value);
  }
  else {
    window.scrollTo(theForm.__SCROLLPOSITIONX.value, theForm.__SCROLLPOSITIONY.value);
  }
  if ((typeof(theForm.oldOnLoad) != "undefined") && (theForm.oldOnLoad != null)) {
    return theForm.oldOnLoad();
  }
  return true;
}

Conclusion


In many scenarios, adding client-side functionality can greatly improve the overall user experience of your web application. Such possibilities were available in ASP.NET 1.x, but ASP.NET 2.0 has added a variety of properties and methods to make it easier to perform a plethora of common client-side tasks. In this article we examined how to set the focus of a Web control, how to associate some client-side action when a Button, LinkButton, or ImageButton was clicked, and how to maintain scroll position across postbacks. Live demos of all of these techniques are provided in the download at the end of this article.

Happy Programming!

  • By Scott Mitchell


    For Equivalent Functionality in ASP.NET 1.x See:


  • Adding Client-Side Message Boxes in your ASP.NET Web Pages
  • Maintaining Scroll Position on Postback
  • Attachments


  • Download the code and examples for this article (in ZIP format)
  • Article Information
    Article Title: ASP.NET.Client-Side Enhancements in ASP.NET 2.0
    Article Author: Scott Mitchell
    Published Date: November 15, 2006
    Article URL: http://www.4GuysFromRolla.com/articles/111506-1.aspx


    Copyright 2017 QuinStreet Inc. All Rights Reserved.
    Legal Notices, Licensing, Permissions, Privacy Policy.
    Advertise | Newsletters | E-mail Offers