In ASP.NET, what are the different ways to inline code in the .aspx?

Can I get a ‘when to use’ for these and others?

<% %>
<%# EVAL() %>



Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Check out the Web Forms Syntax Reference on MSDN.

For basics,

  • <% %> is used for pure code blocks. I generally only use this for if statements

      <div class=”authenticated”>

      <div class=”unauthenticated”>

  • is used to add text into your markup; that is, it equates to

    <div class='<%= IsLoggedIn ? “authenticated” : “unauthenticated” %>’>

  • <%# Expression %> is very similar to the above, but it is evaluated in a DataBinding scenario. One thing that this means is that you can use these expressions to set values of runat=”server” controls, which you can’t do with the <%= %> syntax. Typically this is used inside of a template for a databound control, but you can also use it in your page, and then call Page.DataBind() (or Control.DataBind()) to cause that code to evaluate.

The others mentioned in the linked article are less common, though certainly have their uses, too.

Method 2

You can also use

<%= Class.Method() %>

And it will print the result, just as you can do in Ruby on Rails.

Method 3

Just want to add, there’s also the resources expression

<%$ Resources:resource, welcome%>

and would look for localized version of “welcome” in satellite assemblies automatically.

Method 4

In ASP.NET 4.0, comes <%: %> syntax for writing something html encoded.

<%: "<script>alert('Hello XSS')</script>" %>

The above can be used instead of the belove.
<%= Html.Encode("<script>alert('Hello XSS')</script>")%>

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x