如何在asp.net mvc 3 razor视图中访问应用程序变量?

我在global.asa.cs中设置了一个Application变量:

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

然后尝试使用我的剃刀视图访问:

 @Application["LICENSE_NAME"] 

并得到此错误:

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

什么是正确的语法?

视图不应该从某个地方提取数据。 它们应该使用从控制器操作以视图模型的forms传递给它们的数据。 因此,如果您需要在视图中使用此类数据,正确的方法是定义视图模型:

 public class MyViewModel { public string LicenseName { get; set; } } 

让控制器操作从需要填充它的地方填充它(为了更好地分离您可能使用存储库的关注点):

 public ActionResult Index() { var model = new MyViewModel { LicenseName = HttpContext.Application["LICENSE_NAME"] as string }; return View(model); } 

最后让您的强类型视图向用户显示此信息:

 
@Model.LicenseName

这是正确的MVC模式,应该如何完成。

避免使用像害虫这样的数据,因为今天它是应用程序状态,明天它是一个foreach循环,下周它是一个LINQ查询,并且很快就会在你的视图中编写SQL查询。

 @HttpContext.Current.Application["someindex"] 

您可以使用自动生成的ApplicationInstance属性获取当前的Application:

 @ApplicationInstance.Application["LICENSE_NAME"] 

但是,此逻辑不属于视图。

您应该能够通过HttpContext.Current.Application[]访问它,但是MVC最佳实践会声明您应该考虑通过View Model传递它。

在上面回答的@ Darin-Dimitrov模式的基础上,我将模型传递到局部视图中,我将其加载到_Layout页面中。

我需要在Application Load上从外部资源加载一个网页,该网页将用作跨多个站点的标题导航。 这是在我的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; } 

这是我的部分视图的控制器Action。

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

我像这样在_Layout页面中加载了局部视图。

  

部分视图_Header.cshtml非常简单,只是从应用程序变量加载html。

 @model Models.HeaderModel @MvcHtmlString.Create(Model.NavigationHtml) 
  protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); var e = "Hello"; Application["value"] = e; } 

@ HttpContext.Current.Application [ “值”]