Access session variable in View

2019-04-29 11:53发布

问题:

Since I can't access a session variable in the View, I wonder if I need do add something more to the view to get it to work?

Inside my View:

@Session[ComputerNumber].ToString()

Controller:

Session["ComputerNumber"] = game.RandomNumber();

The error message:

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

回答1:

You can use Session in the view, you just need to use string indexer, just like in your controller. In your case ComputerNumber is not a string, it is a variable which does not exist. Change

@Session[ComputerNumber].ToString()

to

@Session["ComputerNumber"].ToString()

and it should all be working