Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor Pages keep data between class methods

The problem that I have faced lately when trying to write a site on razor pages - when I use variables in a class method, it doesn't keep that data inside. In example: I have a method which creates data when the page is created. And when I press submit button: The data isn't remembered inside the class and thus it returns null.

I've tried to work with Data binding, Temp data, Private classes. Neither of them kept data for a future use inside one class. The current code is:

`

namespace TestSite.Pages.Shared
{
    public class Registration_2Model : PageModel
    {
        private readonly TestSite.Data.ApplicationDbContext _context;

        public UserManager<IdentityUser> _user;

        public string _ID { get; set; }
        public string _Code { get; set; }

        public bool _Validated;

        public Registration_2Model(UserManager<IdentityUser> UserManager, ApplicationDbContext context)
        {
            _context = context;
            _user = UserManager;
        }

        public IActionResult OnGet()
        {
            var CurrentUser = _context.Simple_User.FirstOrDefault(m => m.ID == Guid.Parse(_user.GetUserId(User)));
            if (CurrentUser == null)
            {
                _ID = _user.GetUserId(User);
                _Code = GenerateCode();
                _Validated = false;

                TempData["ID"] = _ID;
                TempData["Code"] = _Code;

                return Page();
            } else { return Redirect("/Index"); }
        }

        [BindProperty]
        public Simple_User Simple_User { get; set; }

        public async Task<IActionResult> OnPostAsync()
        {
            Simple_User.ID = Guid.Parse((string)TempData["ID"]);
            Simple_User.Code = (string)TempData["Code"];
            Simple_User.Validated = false;

            if (!ModelState.IsValid)
            {
                return Page();
            }

            _context.Simple_User.Add(Simple_User);
            await _context.SaveChangesAsync();

            return RedirectToPage("./Index");
        }

        private string GenerateCode()
        {
            Random _random = new Random();
            return $"{_random.Next(1000, 9999).ToString()}-{DateTime.Now.Year}";
        }
    }
}

`

and HTML:

`

@{
    ViewData["Title"] = "Second registration";
}

<h2>Second registration</h2>

<h4>One step left. After your initial registration, you must fill in some blanks, after which, our moderator will check and add you to our list.</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form method="post">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label class="control-label">ID</label>
                <input class="form-control" type="text" placeholder="@Model._ID" readonly />
            </div>
            <div class="form-group">
                <label asp-for="Simple_User.Name" class="control-label"></label>
                <input asp-for="Simple_User.Name" class="form-control" />
                <span asp-validation-for="Simple_User.Name" class="text-danger"></span>
                <span asp-validation-for="Simple_User.Code" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label class="control-label">Code</label>
                <input class="form-control" type="text" placeholder="@Model._Code" readonly />
            </div>
            <div class="form-group">
                <label asp-for="Simple_User.Address" class="control-label"></label>
                <input asp-for="Simple_User.Address" class="form-control" />
                <span asp-validation-for="Simple_User.Address" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-page="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}

}`

Basically, site displays some value in an inaccessible field and should use it when it creates a Simple_User in database. But so far I got only nulls

like image 546
Di1997 Avatar asked Mar 26 '26 16:03

Di1997


1 Answers

HTTP is stateless™. If you want to set properties on objects during the execution of one request, and have those values available for a subsequent request, you need to implement your own state management strategy.

There are a lot of options available to you, depending on what you wan to do. If security is important, you should look at session variables. In the meantime, here are all of the options available: https://www.learnrazorpages.com/razor-pages/state-management

like image 153
Mike Brind Avatar answered Mar 29 '26 06:03

Mike Brind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!