How to use C# constant at ASP.Net page?

constant naming convention in java (4)

The examples given below could make little sense, but it is because I am focusing on syntax.

Let's say I have such C# code:

public static class Foo
  public const string Bar = "hello world.";

Now, I would like to use Foo.Bar constant in ASP.Net instead of typing each time "hello world.". So I used this syntax:

<p><%= Foo.Bar %></p>

It works. It works also in such cases:

<p>"<%= Foo.Bar %>"</p>

<p class="<%= Foo.Bar %>">the weird, nonsense example</p>  

So, it works with quotes too. However I have also cases, when quotes get higher priority:

<custom:Header runat='server' Text="<%= Foo.Bar %>"/>

( header is a custom control -- it simply adds some css by default and position ). In such case quotes marks have higher priority and entire text is sucked as-is, in effect I get header with text

<%= Foo.Bar %>

So, my question is -- what is the syntax to get the value of C# constant, no matter what (IOW -- with highest priority)?


<custom:Header runat='server' Text="<%# Foo.Bar %>"/>

(note hash instead of equal sign) does not work as well.

Answer #1

For a custom control this will work as explained above, so long as your control calls DataBind() internally (for example in WebControl.Render, etc.)

Answer #2

Simple quotes should do the trick

Text='<%= Foo.Bar %>'

or (depending your scenario)

Text='<%# Foo.Bar %>'

Answer #3

You can use databinding expressions in your page as long as the page is databound. You can still use your example:

<custom:Header runat='server' Text="<%# Foo.Bar %>"/>

But you'll also need to ensure that you call DataBind() in your code behind to databind all expressions in your page that are outside of a databinding control.

protected void Page_Load(object sender, EventArgs e)

Answer #4

You need to import namespace in your page <% import namespace="" %>

Oops, sorry, you can't use <%= syntax in server controls. In case of server controls you need to assign it in code. And it doesn't matter if it is constant or just your page class's property.