Saturday, May 26, 2007

 

Check, set, click, whirr


A useful characteristic of most ASP.NET controls, not documented by Microsoft, is an ability to be addressed as ordinary HTML elements while also practicing all their usual ASP.NET behaviors. From JavaScript, for example, ASP.NET checkboxes can be checked, text fields can be filled, and pushbuttons can be pressed. Postbacks will respond in the same ways that they respond to equivalent user actions. Typical JavaScript looks like this:


    var oCheckbox = document.getElementById('<~% = ofCheckbox.ClientID ~>');
    if (oCheckbox != null)
        oCheckbox.checked = true;
 

     var oTextbox = document.getElementById('<~% = ofTextbox.ClientID ~>');
    if (oTextbox != null)
        oTextbox.value = 'Sample text string';


The <~% = ... %~> display blocks reference ID properties of asp.CheckBox and asp.TextBox markup elements, here illustrated as ofCheckbox and ofTextbox. They are needed for compatibility with master pages. See "Mastering and paging JavaScript: Solutions," June 1, 2006.


Hidden pushbuttons are handy for server-side interaction. Just add "display: none" to the Style attributes of an asp.Button element. Typical JavaScript looks like this:


    var oButton = document.getElementById('<~% = ofButton.ClientID %~>');
    if (oButton != null)
        oButton.click();


Hidden textboxes, checkboxes and other controls are an easy way to exchange context information with a server. This approach is simpler than using the also undocumented __doPostBack function sometimes recommended, which requires additional JavaScript enoding and server-side decoding. It minimizes exposure to proprietary features of the Microsoft environment.


[Note: because of display limitations, characters "< " and " >" here are shown with a tilde ~ after or before them.]

Comments: Post a Comment

Subscribe to Post Comments [Atom]



Links to this post:

Create a Link



<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]