Thursday, May 14, 2009

HTML Controls in ASP.Net

The more I use ASP.Net the more I move toward (almost) plain old HTML.

For example:

<asp:Panel id="myPanel" runat="server">
I am in a Panel
</asp:Panel>
<div id="myDiv" runat="server">
I am in a div
</div>

I used to use Panels to conveniently show and hide blocks but I found that I've slowly been moving to using DIV tags with the runat="server" attribute. What's the difference? Well, with a div I get to see and control my markup. With the Panel I don't really know what is going to be rendered. I also get to apply CSS in a way that is consistent with the way I'm applying it to the rest of the page. It can be tricky to apply CSS to ASP.Net controls since I don't know what HTML they might render.

I've found that I don't need to be shy about using runat="server" on regular everyday HTML tags. I use it on TR tags for easy show/hide or server-side modification of attributes (like class or style).

I've also found that using runat="server" on input controls is often much more desirable than using the ASP.Net equivalents.

<asp:checkbox id="myCheckbox" Text="Check Me Out!" runat="server" />
<input type="checkbox" id="myInputCheckbox1" value="10" runat="server" /><asp:Label AssociatedControlID="myInputCheckbox1" runat="server">Check Me Out!</asp:Label>
<input type="checkbox" id="myInputCheckbox2" value="10" runat="server" /><label for="<%=myInputCheckbox2.ClientID%>">Check Me Out!</label>

Why use one over the other? I guess it just depends on what I want to do. The Checkbox control doesn't have a Value property and the HtmlInputCheckBox does. However, the HTML version doesn't have a Text property and I have to provide my own label. HtmlInputCheckBox gives my control over the markup but doesn't provide AutoPostBack.

This is also why I prefer the Repeater over controls like the DataList or GridView. With the Repeater I have control over the markup. And with some help libraries getting things done on the ItemDataBound event is pretty easy.

Just remember that you have options and that even in ASP.Net your run of the mill HTML tags can be empowered as well.

No comments:

Post a Comment