Converting to MVC - Best way to create global variables for layout

时间:2016-10-20 19:54:25

标签: asp.net-mvc razor

I'm coding in Visual Studio 2015. I have a basic (non-MVC) Razor webpage, but am converting it to MVC. I have taken apart the large default.vbhtml page and created several partials. Now I have a layout that calls:

<!--HTML Code Here-->
@RenderPage("_header.vbhtml)
@RenderPage("_sidebar.vbhtml")
<!--HTML Code Here-->
@RenderBody() 
<!--HTML Code Here-->

The index.vbhtml page called by the @RenderBody also pulls in partials (3 of them).

I have some base code (in the original single-page site) that pulls in variables that I use throughout that page and which would be used in each of the partials. That code is:

@Code

Dim webServer as string
Dim reportsServer as string
Dim plantName As String
Dim machineName = Server.MachineName
Select Case Left(machineName, 2)
    Case "P1"
        plantName = "P1 North"
        webServer = "P1N0101"
    Case "P2"
        plantName = "P2 South"
        webServer = "P2S0101"
    Case Else
        plantName = "P5"
        webServer = "P5101"
End Select
Dim ppaDepartments As Database
ppaDepartments = Database.Open("PPA-DB")

Dim ppaLines As Database
ppaLines = Database.Open("PPA-DB")

Dim selectQueryString As String = "Select * from Departments where Tag='" & plantName & "'"
End Code

I am using all of those variables throughout the view and partials. How would I globalize these variables so that I can reference them in each of the partials properly?

1 个答案:

答案 0 :(得分:0)

One of the best ways to handle something like this is to overload the OnActionExecuting method in your controller. I usually create a base controller that all of my other controllers will inherit from and do something like the following:

protected override async void OnActionExecuting(ActionExecutingContext filterContext){
 ViewBag.GlobalVariable1 = webserver;
} 

This action is going to hit anytime anyone grabs a page from your server and before your partial views will fire. I usually cache data with something that will not change frequently so you don't fire off at the DB each time.

And in your partial you can access the data via its ViewBag name.