Search This Blog

Nov 15, 2012

Web Server Controls vs. HTML Server Controls

One of the first possible points of confusion when learning to build web forms is "what is the difference between a Web Server Control and an HTML Server Control?" This probably stems largely from the fact that most of the Web and HTML Server Controls don’t differ much – for example, the Label Web Server Control operates almost identically to the Label HTML Server Control. However, there are some subtle differences between the two.

Web Controls are "server-side" by default; HTML Controls aren’t

When you drag-and-drop a Web Control from the Toolbox onto a Web Form, Visual Studio.NET automatically creates all the necessary code (in both the user interface, and code-behind files) for you to be able to programmatically access and manipulate that control. However, when you drag-and-drop an HTML "Control" onto the form from the Toolbox, all Visual Studio.NET in fact does is insert a piece of plain HTML into the user interface file.

Strictly speaking, the "control" that is inserted would not actually be an "HTML Control" yet. To demonstrate this, Figure 5.1 shows a new Web Form with two Labels added – the top one is a Web Control and the bottom one is an HTML "Control", both dropped from the Toolbox.

<asp:Label id=Label1 runat="server">Label</asp:Label>
<DIV id=DIV1 style="DISPLAY: inline; WIDTH: 70px; HEIGHT: 15px"

For starters, the two entries in the .aspx file look vastly different! Secondly, and more importantly, the second label doesn’t have a green "play" icon on its top-left corner, like the Web Control Label does. This icon indicates that the control it is on is a "server-side control", with the effect that it can be manipulated using server-side ASP.NET code. All server-side controls must include one attribute in their declaration tags – "runat". This attribute must have the value "server".

When ASP.NET is parsing a page and it reaches a tag that has this attribute on it, it knows that it must make the control available to server-side code. Notice that the Web Control Label has a runat
attribute, but the declaration for the HTML Control doesn’t. This is because HTML "Controls" aren’t actually server-side controls by default. However, HTML controls can obviously be made to be accessible on the server side by one of two methods – you can either manually add the runat attribute to the control’s tag in the HTML view, or in the designer, you can right click on the control, and choose the "Run As Server Control" option from the context menu.

Once this option is toggled, the HTML for the control will be modified to include the runat attribute, and the necessary entries will be made in the code-behind (.aspx.vb) file.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...