ASP.NET inline tags

Hey everyone!

Recently I’ve started on my “Professional ASP.NET 4 in C# (and VB)” book to get my knowledge of ASP.NET up.

One of the things I’ve noticed was that nowhere in the first chapter(s) they explained the difference between all the ASP.NET inline tags (such as <% … %>, <%$ … %>, etc)

Therefor I’ve decided to put together this small overview of all the different inline tags and what they do. (Yes, it’s for my convenience too).

This post will cover the following inline tags:

  1. <% … %>
  2. <%= … %>
  3. <%# … %>
  4. <%& … %>

I think it’s obvious what the <%@ … %> tags do 😉
The <%– … –> tags serve as server-side comments. Meaning those comments will not be visible in the HTML source code.

The “<% … %>” tags

This one is probably the most used inline ASP tag there is.
This tag serves the purpose of an embedded code block. It allows a developer to use code (C#/VB) in between normal HTML code.

An example:

Hello world!<br />
It is
<% if(DateTime.Now.Hour < 6 && DateTime.Now.Hour >= 0){ %>
night now!
<% } else { %>
day now!
<% } %>

The “<%= … %>” tags

These tags allow the developer to display something, for example a variable declared in the code behind file, on the page.

They can also be used to display properties of .NET object, such as DateTime:

Hello world!<br />
The time now is <%= DateTime.Now.ToString() %><br />

The “<%# … %>” tags

These tags are used for data binding in databound controls, such as the ListBox, DropDownList, …
The “Page.DataBind()” must be called first, all <%# … %> tags will be evaluated then.

An example that will display the text the user has inputted in another label:

<form id="form1" runat="server">
	Enter some text:
	<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
	<br />
	<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" /><br />
	<br />
	<asp:Label ID="Label1" runat="server" Text="<%# TextBox1.Text %>"></asp:Label>

And then in the code behind:

protected void Button1_Click(object sender, EventArgs e)

The “<%$ … %>” tags

These tags define an expression of one of the following types:

  • AppSettings
  • ConnectionStrings
  • Resources

By using this tag you can gain access to properties or resources within your ASP application.
You could for instance, retrieve a connection string that has been defined inside your web.config file:

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
	ConnectionString="<%& ConnectionStrings:myCon %>"
	SelectCommand="SELECT * FROM Customers">
<asp:CheckBoxList ID="CheckBoxList1" runat="server"
	RepeatDirection="Vertical" RepeatColumns="3"
	DataSourceID="SqlDataSource1" DataTextField="CustomerName">

Mind the “ConnectionString” attribute on the SqlDataSource!

There we go, all inline tags explained!

Happy coding \o/


Leave a Reply

Your email address will not be published. Required fields are marked *