这是我的控制器代码:
private string testVal;
public ActionResult Index()
{
testVal = "test";
return View();
}
public ActionResult NextView()
{
if (testVal == null)
Debug.WriteLine("testVal is null");
return View();
}
更改页面后是否可以记住testVal之类的值?它似乎在重定向时重置值(NextVal中的testVal为null)。
编辑:
我尝试将值保存到会话但Session是null。我正在使用SignalR,当用户连接到页面时,我使用来自集线器的静态事件来通知用户已连接的控制器 - 但是在该事件上运行的内部方法会发生故障。
我的控制器代码:
public ActionResult Index()
{
LoadingHub.userConnected += new EventHandler<IdEventArgs>(UserConnected);
return View();
}
private void UserConnected(object sender, IdEventArgs e)
{
Debug.WriteLine("User Connected with Id: " + e.Id);
if (Session == null)
Debug.WriteLine("Session is null");
}
我的信号中心:
public class LoadingHub : Hub
{
public static event EventHandler<IdEventArgs> userConnected;
//Function informs server that user has connected
public void Connected()
{
Debug.WriteLine("Hub Connected Method");
var id = Context.ConnectionId;
userConnected(this, new IdEventArgs(id));
}
}
答案 0 :(得分:1)
每次发出请求时,都会创建一个新的控制器实例,因此使用私有字段时,您将无法保留此变量的值。
保留它的最简单方法是使用会话。 (如果你想为每个用户群保留这个值)
例如在您的代码中
public ActionResult Index()
{
System.Web.HttpContext.Current.Session["testVal"] = "test";
return View();
}
public ActionResult NextView()
{
if (System.Web.HttpContext.Current.Session["testVal"] == null)
Debug.WriteLine("testVal is null");
return View();
}
答案 1 :(得分:1)
您可以使用cookie或缓存来替换变量。 当你重定向到一个网页时,控制器将被新建,所以你无法获得正确的testVal。但是cookie存储在broswer中。所以你可以设置它并获得。
答案 2 :(得分:1)
您是否查看了ASP.NET服务器端状态管理click here。
这些基本上是在加载新页面后记住服务器上的值的不同方法。
因此,您可以用来记住testVal
的一些服务器端技术是会话状态或应用程序状态。但是,会话状态更适合您的场景,因为它仅适用于用户的当前会话,而应用程序状态存储可在会话之间共享的数据,因此对于全局变量更为理想。
您可以阅读我提供的链接,以便更多地了解差异。
我还想提醒您(正如有人说使用Cookie),用户可以在浏览器上删除或禁用或操作它们,因此这不是一个理想的解决方案。
答案 3 :(得分:1)
您可以使用会话或将数据传递给控制器