0

I am very new to ASP.Net, Razor and MVC.

How i can declare and access a global variable across all the pages in my MVC application ? Sometimes, this variable will be setting its value from java scripts as well.

I tried with Session and Application objects but no use at all.

Any Help ? I saw other posts here but it seems not suitable.

please help.

Jack James
  • 17
  • 1
  • 5
  • 3
    Please rethink if is it needed. If you must use global variables that mean your architecure isn't good enought. For config variable use web.config variables. – Ridikk12 May 12 '17 at 16:31
  • Possible duplicate of [ASP.NET MVC Global Variables](http://stackoverflow.com/questions/5118610/asp-net-mvc-global-variables) – Majid Parvin May 12 '17 at 18:48
  • 1
    @Ridikk12 is right use web.config - and use in controller like - ConfigurationManager.AppSettings["ServiceName"]. Note Returns as string so if int have to parse it. – Shan May 12 '17 at 20:01

2 Answers2

0

For server-side: you can read more here: ASP.NET MVC Global Variables

For javascript: If I were you and I would need to implement such a global javascript variable available on many pages, I would use:

a) local storage or b) cookies

Community
  • 1
  • 1
Marcin Pevik
  • 163
  • 1
  • 14
0

I know you say that session is "no use at all" but that sounds like your simplest solution. You can setup a class to handle reading/writing to session and then reference that in all of your controllers and views.

Create a session variables class...or whatever you want to call it.

using ...
namespace Application.Data
{
    public static class SessionVariables
    {
        private static object GetValue(string AttrName)
        {
            return HttpContext.Current.Session[AttrName];
        }
        private static void SetValue(string AttrName, object AttrValue)
        {
            HttpContext.Current.Session[AttrName] = AttrValue;
        }

        public static int PageIndex
        {
            get => (int?)GetValue("pageIndex") ?? 0;
            set => SetValue("pageIndex", value);
        }
    }
}

To reference in your view...

@using Application.Data
@{
    var index = SessionVariables.PageIndex;
}

This same logic can be used in your controllers.

hack3rfx
  • 573
  • 3
  • 16