views:

37

answers:

2

Can someone explain to me the rules around what can and cannot be evaluated/inserted into markup using the <%# %> and <%= %> tags in asp.net?

When I first discovered I could inject code-behind variables into mark-up using <%= I thought 'great'. Then I discovered that if such tags are present you can then not add to the controls collection of the page (that's a whole different question!). But <%# tags are ok.

Is there a way I can inject a code-behind variable or function evaluation into the page using <%# ? Thanks.

+2  A: 

<%%> are code blocks. You can put any server side code in them. This is a shortcut for <script runat="server"></script>.

<%=%> is for outputting strings. This is a shortcut for <script runat="server">Response.Write()</script>.

See here for more detail about <%%> and <%=%>.

<%#%> are used for data binding expressions.

See the index page for asp.net Page syntax.

Oded
Thanks. Useful info but I'm afraid Prutswonder solved my issue :)
El Ronnoco
+1  A: 

The <%# inline tag is used for data binding, so if you want to use a code-behind variable inside it, you will have to bind the page or control the variable resides in:

Page.DataBind();

You can include this statement in the Page_Load or Page_PreRender event.

See this article for more information about the use of inline tags in ASP.Net, and this article for more about server-side databinding.

Prutswonder
Hi, thanks for your reply. Worked a treat! I'll read the articles when I've a bit more free time!
El Ronnoco