Makach
Makach

Reputation: 7579

How can I reference a constant in a cs from an aspx?

How can I reference a constant from constants.cs in page.aspx, I'm trying the following without any success

<%@ Import  Namespace="MyConstants" %>
<uc:MyControl ID="id1" runat="server" ConstantValue=" <%= Constants.TheValue %>" />
<uc:MyControl ID="id2" runat="server" ConstantValue=" <%# Constants.TheValue %>" />
<uc:MyControl ID="id3" runat="server" ConstantValue=" <%= MyConstants.Constants.TheValue %>" />
<uc:MyControl ID="id4" runat="server" ConstantValue=" <%# MyConstants.Constants.TheValue %>" />

And in Constants.cs

namespace MyConstants
public class Constants
public const string TheValue = "Hello, World";

Upvotes: 4

Views: 788

Answers (6)

Ravi Vanapalli
Ravi Vanapalli

Reputation: 9950

I would suggest you to add static attribute to declaration, & you don't need to create instance of Constant class.

This way you can directly use Constant.TheValue

Happy Coding!!!

Upvotes: 0

Sirwan Afifi
Sirwan Afifi

Reputation: 10824

why do not use the Property for your UserControl?:

UserControl Property :

public string ConstantValue { get; set; }

then you can use it :

<uc:MyControl ID="id" runat="server" ConstantValue="any string" />

Upvotes: 0

Ekk
Ekk

Reputation: 5715

You have to use # with server controls. So, you have to change your code like this one.

<!-- I have no references in page, is that missing? --> 
<uc:MyControl ID="id runat="server" ConstantValue=" <%# Constants.TheValue %>" /> 

Upvotes: 0

Andras Zoltan
Andras Zoltan

Reputation: 42363

Have you tried using the fully qualified class-name?

<%= MyNamespace.MySubNamespace.Constants.TheValue %>

If that works, you can add this namespace to namespaces list in the web.config.

<pages>
  <namespaces>
    <add namespace="MyNamespace.MySubNamespace" />
  </namespaces>
</pages>

And then you won't have to fully-qualify the class name in any page.

Upvotes: 4

RB.
RB.

Reputation: 37232

You need to import your namespace. You do this differently depending on your view engine.

If you're using WebForms:

<%@ Import Namespace="Your.Namespace" %>

If you're using Razor with C#

@using Your.Namespace

If you're using Razor with VB.NET

@Imports Your.Namespace

Upvotes: 4

Habib
Habib

Reputation: 223422

You may specify the namespace for the class in the page as:

<%@ Import Namespace="Your.Name.Space" %>

where Your.Name.Space contains the class Constants

Upvotes: 2

Related Questions