Search code examples
asp.netasp.net-mvcrazorrazor-2razor-pages

Declare Global/Site Wide Variable in ASP.Net VBHTML


After about a thousand years of building websites in ASP Classic, I am trying to learn ASP.Net using Razor. I am using Visual Studio 2012. Google seems to be of no help on some of these basic things (but, I probably just don't know the right question to ask). One of the absolute basic things I am struggling with right now is how to declare a variable that I can use across my website.

For example:

DIM DefaultColor AS String = "Green"

I have that in the _AppStart.vbhtml page and I try to access it using

 <p>@DefaultColor</p>

in the Default.vbhtml, but I get an error saying that DefaultColor is not declared.

  • How and or where do I declare a variable that I can access across the website?
  • If the _AppStart.vbhtml page is the right page, do I need to add something to the default.vbhtml or _template.vbhtml page to load it?

Solution

  • First of all I am not sure if ASP.NET Core is available for VB.NET. At least I tried to create a new project for VB.NET but the ASP.NET Core is not available. I will tell you how you can do it using the C# template.

    You can use the TempData object in order to store and retrieve data. You can set a value like this:

    @{
        TempData["Value"] = "Hello World";
    }
    

    Now you can display this value like this.

    @TempData["Value"]
    

    An other option is to create a static class which will contain the variable which will host the value.

    namespace Sample
    {
        public class MyStaticClass
        {
            public static string Value = "Hello World!";
        }
    }
    

    Now you can display the contents of the value like this:

    @Sample.MyStaticClass.Value
    

    You can also set a value and use it later.

    Sample.MyStaticClsas.Value = "New Value";
    

    I hope it helps.