0

在使用 webmatrix(剃须刀模板,c# 代码)创建的 ASP.NET 网页“站点”中。

我可以在不执行该页面的情况下在 cshtml 模板中设置一个“全局”(AppState)变量吗?

我知道我可以在页面上设置“AppState.Whatever =”,但我必须“访问”页面,以便代码“运行”。

我可以在 te cshtml 模板中设置“Something.Whatever =”,而无需访问模板。这只有在这些页面在保存时被“编译”或解释时才有可能。这样的事情可能吗?

谢谢!

4

2 回答 2

1

您不能将变量设置为_AppStart.cshtml的全局变量。它不会将变量编译到所有页面。您可以尝试将以下内容添加到 _AppStart.cshtml,但它只能将整数添加或编译到您的 cshtml 站点的所有页面。

App.MyInt = 0;

但是,您可以将名为 Global.cs 的文件添加到 App_Code 文件夹

using System;
using System.Collections.Generic;
using System.Web;

/// <summary>
/// This class specifies global variables
/// </summary>
public static class Global
{
    public const string StringName = "Some String";
    public const int IntName = 100;
    // Or anything else you want to add
}
于 2013-10-09T14:55:42.300 回答
1

您可以将名为 _AppStart.cshtml 的文件添加到站点的根目录。它将在您的应用程序发出第一个请求时执行。您可以在其中设置全局变量。

在我的文章中查找标题为应用程序变量的部分:http: //www.mikesdotnetting.com/Article/192/Transferring-Data-Between-ASP.NET-Web-Pages

于 2013-05-13T20:28:37.130 回答