Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you access application variables in asp.net mvc 3 razor views?

I set a Application variable in my global.asa.cs with:

    protected void Application_Start()     {         ...          // load all application settings         Application["LICENSE_NAME"] = "asdf";      } 

and then try to access with my razor view like this:

@Application["LICENSE_NAME"] 

and get this error:

Compiler Error Message: CS0103: The name 'Application' does not exist in the current context 

what is the proper syntax?

like image 785
Chris Avatar asked Mar 12 '11 23:03

Chris


People also ask

How do you access the variable of the controller in the view?

OK, the simple answer is, you need to know the . Net type being returned from your query when you set the scrap variable in your controller. Whatever that type is, that's what type your @model needs to be. Either that, or use the ViewBag --but again, without IntelliSense support since it's a dynamic .

What is razor view in ASP.NET MVC?

Razor is a markup syntax that lets you embed server-based code into web pages using C# and VB.Net. It is not a programming language. It is a server side markup language. Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine. You can use it anywhere to generate output like HTML.


1 Answers

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.

like image 63
Darin Dimitrov Avatar answered Sep 20 '22 16:09

Darin Dimitrov