Home » Development » How to access code-behind variables from the controls that have “runat=server”?

How to access code-behind variables from the controls that have “runat=server”?

Let’s say you have the control below in your ASP.NET page. This is a Telerik control which shows a fancy tile with a text and image.

<telerik:RadImageTile runat="server" ImageHeight="150px" ImageWidth="150px" ImageUrl="http://www.mysite.com/tile.png" Name="Test Tile" NavigateUrl="http://www.microsoft.com" Target="_blank">

You want to embed ImageUrl dynamically instead of hardcoding it as it’s above. You may want to use this format but it doesn’t work since there is runat="server" tag in the control.

<%= testVariable %>

In order to reference code-behind variables from your controls that have runat="server" tag, follow the steps below.

1- Create CodeExpressionBuilder class in your Solution root

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.Compilation;
using System.CodeDom;

namespace Namespace_Name
    public class CodeExpressionBuilder : ExpressionBuilder
        public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
            return new CodeSnippetExpression(entry.Expression);

2- Add expressionBuilders block into web.config

<compilation debug="true" targetFramework="4.5.2">
          <add expressionPrefix="Code" type="iFin_Production.CodeExpressionBuilder"/>

3- Refer your variable in ASP.NET page as it’s shown below

<telerik:RadImageTile runat="server" ImageHeight="150px" ImageWidth="150px" ImageUrl="<%$ Code: testVariable %>" Name="Test Tile" NavigateUrl="http://www.microsoft.com" Target="_blank">


Ned Sahin

Blogger for 20 years. Former Microsoft Engineer. Author of six books. I love creating helpful content and sharing with the world. Reach me out for any questions or feedback.

Leave a Comment