Monday, September 13, 2010

Web Controls in ASP.NET

When we drag a control from the Web Controls section of the toolbox onto a form, VS.NET automatically gives the tag a runat=”server” attribute and an ID. The IDE also automatically adds a protected field to our code behind class for us to interact with the control programmatically. In the following example we have dragged a TextBox control onto the web form, and adjusted the appearance using the Properties window of the web form designer.


<asp:TextBox id="TextBox1" runat="server" Font-Names="Courier New"/>

We can also interact with this control from code behind.

protected System.Web.UI.WebControls.TextBox TextBox1;
private void Page_Load(object sender, System.EventArgs e)
{
          TextBox1.Text = "Foo Berry Tea";
          TextBox1.BackColor = Color.LightGray;
          TextBox1.ForeColor = Color.Red;
}

Notice the web control version of a textbox operates at a slightly higher level of abstraction when compared to the HTML control. For example, the TextBox control has properties to set the colors (BackColor, ForeColor). We don’t need to know how to use inline styles – the code for the control will take care of rendering the correct HTML to achieve the desired appearance in the client’s web browser.

The web controls section of the toolbox also offers some controls you won’t find in pure HTML. These controls, like the RegularExpressionValidator, produce a combination of HTML and JavaScript on the client to offer more functionality than you can get from available HTML controls.

The web control approach is object oriented, easier to use server-side, and more robust than using HTML controls. Since everything in software development has a trade-off, you might be wondering what the downside to using a web control is (some may say the trade-off is performance, but in reality the overhead of using a web control is almost negligible). There really is no downside to using web controls over HTML controls – we should always favor using the web control.

The next question then might be: why did Microsoft give us two sets of controls if web controls are always superior? One answer might be that HTML controls offer a path for porting HTML and ASP applications to .NET. Just give an HTML tag a runat and ID attribute and one can start using the control from code-behind. Another answer is that we can still find scenarios where HTML controls are useful in brand new .NET applications.

No comments:

Post a Comment