Does asp.net MVC have Application variables?
Yes, you can access Application variables from .NET MVC. Here's how:
System.Web.HttpContext.Current.Application.Lock();
System.Web.HttpContext.Current.Application["Name"] = "Value";
System.Web.HttpContext.Current.Application.UnLock();
MVC access application variable in controller
For example, in global.asax:
Application["AppVar"] = "hello";
In any controller method:
string appVar = HttpContext.Application["AppVar"] as string;
Update (7/2018):
If you need to access MVC global application data from a DLL library:
using System.Web;
....
if (HttpContext.Current != null && HttpContext.Current.Application != null)
string appVar = HttpContext.Current.Application["AppVar"] as string;
It is safer to check HttpContext.Current.Application against null as well, because some fake httpcontext library (used in unit test projects) could have a valid context with null "Application".
what is application variable? How do i declare Application variables in ASP.NET MVC?
In global.asax file
first declare service in which you write linq syntax or your logic,
private readonly ISystemConfigurationService _systemConfigurationService;
Then, create constructor
public MvcApplication()
{
_systemConfigurationService = new SystemConfigurationService();
}
Get Model Data when app start
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
List<SystemConfigurationModel> systemConfigurationValue = General.MapList<System_Configuration , SystemConfigurationModel> (_systemConfigurationService.GetAllSystemConfigData());
Application["SystemConfig"] = new List<SystemConfigurationModel>(systemConfigurationValue);
}
In controller you have to do this,
List<SystemConfigurationModel> applicationState = HttpContext.Application["SystemConfig"] as List<SystemConfigurationModel>;
ViewBag.ContactEmail = applicationState.Find(x => x.Config_Key == "ContactMail").Value;
Then Pass it to view using view bag.
How do you access application variables in asp.net mvc 3 razor views?
Views are not supposed to pull data from somewhere. They are supposed to use data that was passed to them in form of a view model from the controller action. So if you need to use such data in a view the proper way to do it is to define a view model:
public class MyViewModel
{
public string LicenseName { get; set; }
}
have your controller action populate it from wherever it needs to populate it (for better separation of concerns you might use a repository):
public ActionResult Index()
{
var model = new MyViewModel
{
LicenseName = HttpContext.Application["LICENSE_NAME"] as string
};
return View(model);
}
and finally have your strongly typed view display this information to the user:
<div>@Model.LicenseName</div>
That's the correct MVC pattern and that's how it should be done.
Avoid views that pull data like pest, because today it's Application state, tomorrow it's a foreach
loop, next week it's a LINQ query and in no time you end up writing SQL queries in your views.
ASP.NET MVC Application Variables?
You can store application-wide data in the ASP.NET Cache.
Add your item to the cache using the Cache.Insert method. Set the sliding expiration value to a TimeSpan of 5 minutes. Write a wrapper class for accessing the object in the cache. The wrapper class can provide a method to obtain the object from the cache. This method can check whether whether the item is in the cache and load it if it isn't.
For example:
public static class CacheHelper
{
public static MyObject Get()
{
MyObject obj = HttpRuntime.Cache.Get("myobject") as MyObject;
if (obj == null)
{
// Create the object to insert into the cache
obj = CreateObjectByWhateverMeansNecessary();
HttpRuntime.Cache.Insert("myobject", obj, null, DateTime.Now.AddMinutes(5), System.Web.Caching.Cache.NoSlidingExpiration);
}
return obj;
}
}
Access Application object in ASP.Net MVC to store application wide variables
In a controller you should be able to do this:
this.HttpContext.Application["foo"] = "bar";
Global Variables MVC application
Yes, you can use session, which is global to the current user only:
HttpContext.Current.Session["Login"] = "John Doe";
However, you won't do that in global.asax because Session is a module that gets initialized at a very specific time (see this). As such, you most likely want to do it in the controller at an appropriate time:
public ActionResult Index()
{
this.HttpContext.Session["Login"] = "X";
}
As an oversimplified example.
Related Topics
Getting Hash of a List of Strings Regardless of Order
How to Print Out a Tree Structure
Deferred Execution and Eager Evaluation
How to Align Text in Columns Using Console.Writeline
Determine Assembly Version During a Post-Build Event
How to Loop Through a List<T> and Grab Each Item
Are 2 Dimensional Lists Possible in C#
Self Referencing Loop Detected - Getting Back Data from Webapi to the Browser
.Include() VS .Load() Performance in Entityframework
How to Route Images Using ASP.NET MVC Routing
Binding Objects Defined in Code-Behind
What Is the Efficiency and Performance of Linq and Lambda Expression in .Net
When Is Finally Run If You Throw an Exception from the Catch Block