views:

87

answers:

4

This may be a very dumb question but I can't seem to get it working. I use at many places the following syntax for dynamically binding a property of a control in aspx file to the resource entry, e.g.

<SomeFunnyControl Text="<%$ Resources : ResClass, ResEntry %>" />

I want to do a similar thing with a class containing some constants, something like

<SomeFunnyControl Text="<%= MyConstantsClass.MyStringConstant %>" />

But this doesn't seem to work, it simply sets the text to the exact expression without evaluating it. I am using ASP.NET 3.5 btw.

I have tried the databinding approach but I get an HttpParseException saying

Databinding expressions are only supported on objects that have a DataBinding event.

+1  A: 
<asp:Label ID="lbl" Text="<%# SomeText %>" runat="server" />

Then call lbl.DataBind(); or databind some container of the label.

CRice
Ok, I have to admit I simplified it a little bit, I'm not doing it for labels but for some properties nested in controls I can't really influence so much. Is there no easier way ?
Thomas Wanner
When you databind those controls it should work in a similar fashion
CRice
Maybe post a more exact example?
CRice
+2  A: 

Your code should look like this:

<asp:Label ID="lblMyStringConstant" runat="server" Text='<%# MyConstantsClass.MyStringConstant %&>'></asp:Label>

You also need to call DataBinding on that control, like this:

lblMyStringConstant.DataBind();

(It is not necessary if you are calling DataBind on entire Page or parent container of this label, because it will call DataBind for all its children)

tpeczek
A: 

If you have it like this it should work actually:

public static class MyConstantsClass
{
   public static string MyStringConstant = "Hello World!";
}

or alternatively

public class MyConstantsClass
{
   public const string MyStringConstant = "Hello World!";
}

If you declare it like

<asp:Label ID="Label1" runat="server" Text="<%= MyNamespace.MyConstantsClass.MyStringConstant %>"></asp:Label>

it won't work and the output will be "<%= MyNamespace.MyConstantsClass.MyStringConstant %>".

What you could do alternatively is to write it like this:

<asp:Label ID="lblTest" runat="server"><%= MyNamespace.MyConstantsClass.MyStringConstant %></asp:Label>

This works perfectly for me, but note you have to provide the fully qualified namespace to your class in the ASPX definition. At least otherwise it didn't work for me.

Juri
+2  A: 

This article: The CodeExpressionBuilder might be interesting/helpful (although written for ASP.NET 2.0).

It (seems) to enable you to write ... Text="<%$ Code: DateTime.Now %>" .... That might help, no? It is quite a bit of overhead, though.

scherand
That's really cool, thanks a lot ;)
Thomas Wanner