tags:

views:

51

answers:

1

I'm confused which one is better.

ASPX:

<asp:HyperLink ID="HyperLink1" runat="server">HyperLink</asp:HyperLink>

Code:

String url = "http://stackoverflow.com";
if(IsShow)
{
    HyperLink1.Visible = true;
    HyperLink1.NavigateUrl = url;
}

and the second option is:

<%if(IsShow){%>
<a href="<%=url%>">HyperLink</a>
<%}%>

This two ways to do exactly same.

Which one is better, and why?

+4  A: 

It's mainly for readability that the first one is preferred (although the code you pasted is invalid - you need to wrap it in a script tag and specify the function (ie Page_Load) to do your logic.

Secondly, the second method gets executed on Page_PreRender, so you are limited by performing logic late in the page life cycle. You will notice this method when programming in ASP.NET MVC (as there is no code-behind model).

Use the first method in Web Forms, the second one in ASP.NET MVC.

RPM1984
But if I need to modify the link, the first option need to be compiled. and the second option dont need to compiled. This means i can react immediately.. isn't it?
sunglim
ASP.NET control consume more server resource in general as an instance of the control need to be created. Personally I avoid using ASP.NET control or use a plain HTML runat="server" only.
airmanx86
It still needs to be compiled. The "IsShow" and "url" properties are server properties. The page lifecycle will still kick in, which causes all page properties to be evaluated. In this example, you dont need any server code. Just render out the URL and IsShow to the client as variables (using RegisterClientSideScript), and use them within a regular HTML anchor tag.
RPM1984