ceuben
ceuben

Reputation: 329

How to create global constant variables in asp.net MVC 5

I'm searching for a way to create a global constant variable, which I can use in my controllers.

I've totally no idea how to create that.

Thanks in advance

Upvotes: 7

Views: 17858

Answers (2)

Kryszal
Kryszal

Reputation: 1673

Very comfortable way is to use Strongly-Typed Settings for that. You can access to these variables everywhere in a project and change its values without recompilation.

You can use Visual Studio editor to define settings (Project > Properties > Settings):

Settings VS Editor

These variables will be added to an appropriate section in a Web.config or App.config file in this way:

<setting name="SomeStringVariable" serializeAs="String">
   <value>SomeStringValue</value>
</setting>
<setting name="SomeBoolVariable" serializeAs="String">
   <value>false</value>
</setting>
<setting name="SomeDoubleVariable" serializeAs="String">
   <value>1.23</value>
</setting>

You can use defined variables anywhere in your project in a simple way:

string myStringVariable = Settings.Default.SomeStringVariable;
bool myBoolVarialbe = Settings.Default.SomeBoolVariable;
double myDoubleVariable = Settings.Default.SomeDoubleVariable;

Upvotes: 19

Debasish
Debasish

Reputation: 369

1: generate a static class(say Constant.cs)

set the property as

public static string YourConstant{
get { return "YourConstantValue";}}

accesses it anywhere

Constant.YourConstant;

or 2. you can also use web.config

<appSettings><add key="YourConstant" value="YourConstantValue" /></appSettings>

Use it as

ConfigurationManager.AppSettings["YourConstant"];

Upvotes: 13

Related Questions