我是ASP.Net,Razor和MVC的新手。
如何在MVC应用程序的所有页面中声明和访问全局变量?有时,此变量也将从java脚本中设置其值。
我尝试使用Session和Application对象但根本没用。
任何帮助?我在这里看到了其他帖子,但似乎不合适。
请帮忙。
答案 0 :(得分:0)
对于服务器端: 你可以在这里阅读更多内容:ASP.NET MVC Global Variables
对于javascript: 如果我是你,我需要在许多页面上实现这样的全局javascript变量,我会使用:
a)local storage或 b)cookies
答案 1 :(得分:0)
我知道你说会话“完全没用”,但这听起来像是你最简单的解决方案。您可以设置一个类来处理读/写会话,然后在所有控制器和视图中引用它。
创建一个会话变量类......或者你想要调用它的任何东西。
using ...
namespace Application.Data
{
public static class SessionVariables
{
private static object GetValue(string AttrName)
{
return HttpContext.Current.Session[AttrName];
}
private static void SetValue(string AttrName, object AttrValue)
{
HttpContext.Current.Session[AttrName] = AttrValue;
}
public static int PageIndex
{
get => (int?)GetValue("pageIndex") ?? 0;
set => SetValue("pageIndex", value);
}
}
}
在您的视图中引用...
@using Application.Data
@{
var index = SessionVariables.PageIndex;
}
可以在控制器中使用相同的逻辑。