Question

I have read many articles and documentation and still its not clear to me what i can include in the global.asax and _AppStart.cshtml files.

I tried putting simple things like

@{
    var rlist = new List<string>();
    rlist.Add("Value1");
    rlist.Add("Value2");
}

in both of the files and tried to use them in my Default.cshtml with no luck..it says its not defined in the context.

I thought that this code would be recognizable everywhere.

The only way i have found that it works ONLY for _AppStart.cshtml is by assigning my var to AppState dictionary:

@{
    var rlist = new List<string>();
    rlist.Add("Value1");
    rlist.Add("Value2");
    AppState["rlist"] = rlist;
}

Then i can reference through my pages the rlist variable by something like this:

var soulis = ((List<string>) AppState["rlist"]);

In Global.asax the above doesn't work..

Can someone explain what is happening?

Was it helpful?

Solution

AppStart is a Web Pages framework file that executes once when the application first starts just like Global.asax. I suspect it was designed specifically to shield beginners from all the events that Global.asax includes by default when that file is generated by Visual Studio/WebMatrix.

You can use Global.asax to hook into specific events to execute any code you like.

AppStart is designed more for simple things like initialising helpers e.g. the WebSecurity helper, or for setting global variables. If you declare variables, they will only be accessible across the application if they are declared as global. You have discovered one way to do that:

AppState["rlist"] = rlist;

Or you can use the dynamic features of Web Pages:

App.rlist = rlist;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top