Accessing form UI elements in your ASP.NET code-behind

I can’t believe that in 2011, when .Net has been around over 8 years and is in version 4.0 now (It’s 6th release, BTW (1.0, 1.1, 2.0, 3.0, 3.5, 4.0)), that people are still coding like this to access form elements:

 <input id="username" name="username" type="text">
<input id="password" name="password" type="password">

 string userName = Request.Form["username"];
string passWord = Request.Form["password"];

if(userName.IndexOf("@") > 0)
{
//do this
}
else
{
//do that
}

Click here to follow me on Google+.

That may have been necessary back in the old classic asp days, but there’s a way to do it that’s fully object oriented AND compile-time checked (as well as IDE editing time checked too!):

First, I wouldn’t use HTML elements, I’d use serverside objects, like this:

 <asp:TextBox ID="UserNameTextBox" runat="server">asp:TextBox>
<asp:TextBox ID="PassWordTextBox" runat="server" type="password">asp:TextBox>
 

(side note: Give objects names that say what they are, such as appending “TextBox” to TextBox objects, and put it at the end, so that it reads like you speak.)

But, if you insist on using HTML elements, add runat=”server” to them.  That way, the code-behind can have access to them as objects.


 <input id="UserNameInput" runat="server" type="text">
<input id="PassWordInput" runat="server" type="password">

 if(this.UserNameTextBox.Text.Contains("@"))
{
//(yes, I realize I ref’d UserNametTextBox
        //and not UserNameInput… Look at the code further up…)
}
else
{
//do that
}

The benefits of this are many-fold:

  1. Server-side objects have lots of extra capability since they’re fully object oriented objects.
  2. Adding runat=”server” to any element (including plain old HTML elements) makes them actual objects, accessible from your code-behind.
  3. While in the code-behind, you can type this. (or me. in VB.Net), as soon as you type the period, you’ll get intellisense popping up listing your GUI elements.
  4. Intellisense prevents typos.
  5. Since you’re referencing actual objects, the IDE will detect whether you have a typo and put the red squiggles underneath it in addition to adding an entry to your errors list in your errors view.
  6. The compiler will catch any typos or references to objects that don’t exist.
  7. You’ll catch errors before you publish your code, preventing your customers from finding the bugs, making you look bad.
  8. Since you’re catching bugs earlier, you’ll spend less time fixing your bugs that your customer finds, saving your customer money and embarrassment.

See this image?

image_thumb26

You’ll find an actual working version of it at the bottom of this article. Please click the appropriate buttons in it to let your friends know about this article.

Check back later for updates too!

Click here to follow me on Google+.

Leave a Reply