简体   繁体   中英

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

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)?

Edits:

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

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

Try to avoid having c# code other than in the code behind. Better put a label control in the aspx page and set it's text property with Foo.Bar

myLabel.Text = Foo.Bar;

You then have all server side code in the code behind, it is much cleaner and readable for others.

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)
{
    DataBind();
}

对于自定义控件,只要您的控件在内部调用DataBind() (例如在WebControl.Render等中),这将如上所述起作用。

Simple quotes should do the trick

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

or (depending your scenario)

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

You need to import namespace in your asp.net page <% import namespace="namespace.of.foo.class" %>

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.

afaik the value in <%= is used during the render stage of the page lifecycle

the controls need those values earlier in the lifecycle. Using <%# will happen during databinding.

Another option is to just set it on Page_Load. Its the way its supposed to be used in regular asp.net. Alternatively you can set it even earlier / during init (do if you are not manipulating it).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM