Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What other objects are accessible inside <%# %> tags in aspx?

I run into similar codes like this all the time in aspx pages:

<asp:CheckBox Runat="server" ID="myid" Checked='<%# DataBinder.Eval(Container.DataItem, "column").Equals(1) %>'>

I was wondering what other objects I have access to inside of that <%# %> tag. How come DataBinder.Eval() and Container.DataItem are not visible anywhere inside .CS code?

like image 693
Haoest Avatar asked Dec 14 '22 06:12

Haoest


2 Answers

Within <%# %> tags you have access to

  1. Anything that is visible in your code-behind class (including protected methods and properties).
  2. Anything declared on the aspx page using <@import @>.
  3. Anything passed in as the event arguments when the ItemDataBound event is fired (e.g. RepeaterItemEventArgs, DataListItemEventArgs, etc).

Container is actually a wrapper for RepeaterItemEventArgs.Item, DataListItemEventArgs.Item, etc. So you can actually access it in code behind within your ItemDataBound events as e.Item (e normally being the event arguments parameter name).

DataBinder is also accessible in code behind by using System.Web.UI.DataBinder.

On a side note, casting the Container.DataItem is preferred over using Eval. Eval uses reflection so there's an overhead there. In VB.NET it would be something like

<%#DirectCast(Container.DataItem, DataRow)("some_column")%>

Or C#

<%#((DataRow)Container.DataItem)["some_column"].ToString()%>
like image 183
Fung Avatar answered Jan 06 '23 12:01

Fung


I believe you have access to anything within scope of the page class, though the results of the expression are converted to a string, so you can't embed conditional expressions the way you can with "<%" expression holes.

Here is a nice blog post which dives under the covers of the generated ASPX class.

Hope this helps.

like image 37
ckramer Avatar answered Jan 06 '23 12:01

ckramer