Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

asp.net

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";
like image 748
Makach Avatar asked Dec 27 '22 16:12

Makach


2 Answers

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
like image 182
RB. Avatar answered Dec 29 '22 06:12

RB.


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.

like image 25
Andras Zoltan Avatar answered Dec 29 '22 04:12

Andras Zoltan