Home > Point2 - Technical > ASP.NET Data-Bind tag vs. Evaluation tag ‘Gotcha’

ASP.NET Data-Bind tag vs. Evaluation tag ‘Gotcha’

August 2, 2012

My team ran into an interesting problem today while trying to fix a NullReferenceException from within an ASPX page. We had the following (simplified) code in the page:

<span>MyString # of characters: <%# MyString.Length %></span>

Of coarse, when MyString was null, this page was throwing the NullReferenceException. To solve this, we added a null check around the whole block.

<% if (MyString != null) { %>
    <span>MyString # of characters: <%# MyString.Length %></span>
<% } %>

By making this change, our understanding was that the inner block should not be evaluated by the server because of the conditional check around it. We tested this out with the case where MyString was null. To our surprise, we still got a NullReferenceException but this time with more details. The stack trace eluded tho the problem stemming from a DataBind() invocation.

The problem with this code is that we are attempting to use a DataBind expression in our ASPX page. DataBind constructs (<%# %>) get evaluated by the DataBind() method regardless of what conditional constructs surround them in the page. This mistake was simply caused by our inexperience ASP.

The solution was to switch the DataBind expression to, what I will call, an Evaluation expression. These expressions are the ones with the <%= %> syntax. I call them “evaluation” expressions because the documentation doesn’t refer to them as anything other than “the <%= %> construct”. They don’t use the DataBind functionality at all. Instead they are the equivalent of calling Response.Write() from within your page; they output the result of the expression as plan text into your markup. Our working solution looks like this:

<% if (MyString != null) { %>
    <span>MyString # of characters: <%= MyString.Length %></span>
<% } %>

A more seasoned ASP.NET developer may have thought “Duh, don’t do that” but it may not be so obvious to others. Unfortunately, I have seen DataBind and Evaluation expressions used almost interchangeably in many applications. They have different purposes and the differences between them need to be understood to be effective in ASP.NET. To learn these differences and understand when to use one vs. the other, I found the following resources helpful.

What are these special tags: <%# and <%= (Microsoft ASP.NET Forums)

ASP.NET Databinding/Server tags differences, declarative output property? (StackOverflow)

%d bloggers like this: