Reputation: 3470
First of all, I am new to ASP.NET. I'm trying to create sudoku on a website, but I have one problem.
I show the sudoku field with the HomeController method -> ActionResult index();
In this ActionResult I create a new SudokuField and show it on the website. This works.
I also added a @html.ActionLink in my Index.cshtml like this:
@Html.ActionLink("Cheat", "Index", new { @no = 2 })
When I click on "Cheat", it calls the Index() method again from the HomeController and gives number 2 as parameter, works fine. But because the Index() method is called again, the HomeController creates a new Sudoku object. So I lose the current state of the GameField.
My Question: Is there a solution that the HomeController will not make a new object of Sudoku.
My HomeController ->
SudokuBasis.Game myGame = new SudokuBasis.Game();
Models.Sudoku s = new Models.Sudoku(); // Sudoku Object
public ActionResult Index(int? no) {
if (no == null) {
myGame.Create(); // creates all fields and add some value
} else if (no == 2) {
myGame.Cheat(); // fills all fields
}
s.MyFields = myGame.GameField();
return View(s);
}
Upvotes: 1
Views: 2003
Reputation: 14250
Every request will create a new controller instance so you'll need to move the game creation into an action.
You could store the sudoku instance in Session
then when you cheat you can check if an instance exists rather than create a new one.
public ActionResult NewGame()
{
var game = new Game();
Session["game"] = game;
return View(game);
}
public ActionResult Cheat()
{
if (Session["game"] == null)
{
return RedirectToAction("NewGame");
}
var game = Session["game"] as Game;
return View(game);
}
Upvotes: 4