Inline Server Tags | ASP .NET

30 Jul

I have to tell you: Sometimes I get confused on which server-side tag I should use to make my codes. Normal since I never use all of them so often. If you suffer from the same issue this text might be useful as a quick reference. Copied.

<% .. %>, <%= .. %><%: .. %>, <%– .. –%>, <%# .. %>, <%$ .. %>, <%@ .. %>

<% … %>

The most common of the inline tags. It’s used when you need to make some small code on the aspx page or render some expression there. For example:

<% if(isAdmin) { %>
Hello Admin!
<% } %>

<%= … %>

This is the simplest way to display some information in an ASP.NET page. The equal sign acts as Response.Write rendering the object directly on the page. For example:

Today is <%= DateTime.Now %>

<%: %>

This was implemented in ASP.NET 4 and it’s basically the same as above but with one small thing: This server tag automatically does the HTML Encoding for you. So, instead of using Server.HtmlEncode(htmlText) on your code you can simply use as the example:

Here is some html <%: htmlText %>

<%– … –%>

This tag is a server-side comment. Since this code is not rendered on the browser you can use it in case you don’t want anyone to see the comments you leave on the system. Example:

<%-- Nobody is gonna see this --%>

<%# … %>

If you want to do some data binding, you have to use this tag. It can be used with DataBinder.Eval(), DataBinder.Bind() or any member which you have in the page (public or protected). The only “problem” is that you have to use these tags only in server-side elements (with runat=”server”). You will find this tag being used in some controls such as GridView, DetailsView and Repeater. Example:

<asp:Repeater ID="rptUsers" DataSourceID="Users" runat="server">
         <%# Eval("LastName") %>, <%# Eval("FirstName") %>

<%$ %>

This one is used to evaluate expressions in a configuration file. For example:

<asp:SqlDataSource ID="SqlDataSource1" Runat="server" 
    SelectCommand="SELECT * FROM [Employees]"
    ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString1 %>">

<%@ %>

This tag is used to specify the settings used by the page and user controls. Example:

<%@ Page Language="VB" ContentType="text/xml" %>
Leave a comment

Posted by on July 30, 2014 in ASP .NET



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: