30

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?

5
  • Application variables? As in the .config file appSettings? (Please be more specific) Commented Mar 12, 2011 at 23:28
  • 4
    @Brad, He means Application state variables, if you look at the code it is pretty specific. Commented Mar 12, 2011 at 23:32
  • @Brad: I think he means values in the Application state object. Commented Mar 12, 2011 at 23:32
  • 1
    @Sanjeevakumar/@CodemOnkey: Dually noted. Thanks. ;-) Commented Mar 12, 2011 at 23:35
  • @BradChristie dually noted, ha! I see what you did there. Commented Feb 27, 2020 at 19:35

7 Answers 7

64

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.

Sign up to request clarification or add additional context in comments.

6 Comments

+1 for pointing not only to a solution of the problem, but one that better follows the MVC pattern.
You can also create separate ActionResult that renders a partial view if you need to reuse some code, like in a header menu. I needed to send a model into a PartialView from my _Layout page, and wanted reusable code. I followed this pattern, and used @{Html.RenderAction("ActionName", "ControllerName");}. The Action returned a partial view.
Hi, I use same pattern but some code use static variables instead of application state. I'm really wondering what is right way?
How do you set data for the _layout view?
This solution really helped me to understand the separation between view and controlle. Thanks kind sir, and +1. As a side note, there are more answers here at SO using linq queries in View than not.... maybe there's something we can do?
|
25
@HttpContext.Current.Application["someindex"]

Comments

6

You can get the current Application using the automatically generated ApplicationInstance property:

@ApplicationInstance.Application["LICENSE_NAME"]

However, this logic does not belong in the view.

1 Comment

This works, but Visual Studio and or Resharper does not like it. The IDE likes the @HttpContext.Current.Application["someindex"] better, even if they are not best practices.
5

You should be able to access this via HttpContext.Current.Application[], however MVC best practices would state that you should probably consider passing this through your View Model.

Comments

4

Building on @Darin-Dimitrov pattern answered above, I passed a model into a partial view, which I loaded into a _Layout page.

I needed to load a web page from an external resource on Application Load, which will be used as the header navigation across multiple sites. This is in my Global.asax.cs

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    Application["HeaderNav"] = GetHtmlPage("https://site.com/HeaderNav.html");
}

static string GetHtmlPage(string strURL)
{
    string strResult;
    var objRequest = HttpWebRequest.Create(strURL);
    var objResponse = objRequest.GetResponse();
    using (var sr = new StreamReader(objResponse.GetResponseStream()))
    {
        strResult = sr.ReadToEnd();
        sr.Close();
    }
    return strResult;
}

Here is my controller Action for the partial view.

public class ProfileController : BaseController
{
    public ActionResult HeaderNav()
    {
        var model = new Models.HeaderModel
        {
            NavigationHtml = HttpContext.Application["HeaderNav"] as string
        };
        return PartialView("_Header", model);
    }
}

I loaded the partial view in the _Layout page like this.

<div id="header">
     @{Html.RenderAction("HeaderNav", "Profile");}
</div>

The partial view _Header.cshtml is very simple and just loads the html from the application variable.

@model Models.HeaderModel
@MvcHtmlString.Create(Model.NavigationHtml)

Comments

1
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RouteConfig.RegisterRoutes(RouteTable.Routes);

        var e = "Hello";
        Application["value"] = e;
    }

@HttpContext.Current.Application["value"]

Comments

0

I had this issue in an MVC controller and had to make fully qualified HttpContext for it to work ..

System.Web.HttpContext.Current.Application["VarName"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.