Search code examples
c#.netrazor-pages

Razor Pages public field becomes NULL when onPost() triggered


Beginner in Razor pages, hopefully someone could help me. I have input form on html which binds to some fields of GameConfig Game (works perfectly). All fields got updated and I can save Game in DB.

Now I was trying to add GameBoard[] GameBoards and initializing individual Gameboard[0] and GameBoard[1] in array in OnGet(). Whenever onPost() is triggered Gameboard[0] and GameBoard[1] become NULL. I don't understand why is this happening.

I simply want to update not only GameConfig Game in onPost(), but add coordinates in the GameBoards too.

Thank you in advance for help!

public class StartModel : PageModel
{
    private readonly AppDbContext _context;

    [BindProperty] public GameConfig Game { get; set; }

    public GameBoard[] GameBoards = new GameBoard[2];

    public StartModel(AppDbContext context)
    {
        _context = context;
    }

    public async Task<IActionResult> OnPostAsync(int id)
    {
        Game = await _context.GameConfigs
            .FirstAsync(m => m.GameConfigId == id);

        // TODO: Update some information on GameBoards
        
        _context.GameConfigs.Update(Game);
        await _context.SaveChangesAsync();

        return Page();
    }

    public async Task<IActionResult> OnGet(int? id)
    {
        Game = await _context.GameConfigs
            .FirstAsync(m => m.GameConfigId == id);

        GameBoards[0] = new GameBoard(Game.BoardSizeX, Game.BoardSizeY);
        GameBoards[1] = new GameBoard(Game.BoardSizeX, Game.BoardSizeY);

        return Page();
    }
}

Solution

  • Each request results in an entirely new instance of the StartModel being initialised. Pages do not maintain state across requests. That is how the web works - it is stateless by design. You have to implement your own state management strategy if you want to persist state across requests. There are plenty of options available to you: https://www.learnrazorpages.com/razor-pages/state-management

    Since you only need 4 pieces of data to construct your array, you should look at using hidden fields to store the parameter values, which will be included in the form when it is posted back.