DubDub
DubDub

Reputation: 1377

Object being lost after post on .net core

I'm developing a little web application using .Net Core Razor pages and I'm quite new to using it.

I have a object that has the [BindProperty] attribute assigned to it, and it is basically describing a user's login and password for logging into a database, and a few other details I haven't set up yet.

The object is set up in the OnGet() method and the page is returned.

Now, they press a connect and successfully connect to the database and all is good, they successfully connect to the database, and more information is displayed to the user.

I also have a disconnect button which should remove all the details on connecting to the database from the object, however when I click the disconnect button, the object is now null and lost.

This is a problem as it's like the values are saved on the first post, but they're not saved on the second post or even exist for the second post.

Again, I'm new to .net core and I'm sure I've made some rookie mistake, but I can't see it, thanks all.

[BindProperty]
public CreatorInputs Inputs { get; set; }

public async Task<IActionResult> OnGetAsync()
{
    Inputs = new CreatorInputs();
    return Page();
}

public async Task<IActionResult> OnPostConnectToDatabase()
{
    // Assign values to connect to database
    // Connect to database successfully
    // Add data from the database to be displayed to user
    return Page();
}
* Inputs is not null when we finish this method

* Inputs is null when we hit this method
public Task<IActionResult> OnPostDisconnectFromDatabase()
{
    Inputs = null;
    return OnGetAsync();
}

I'm sure it's just an error in my understanding, but I can't see what.

Upvotes: 0

Views: 1618

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239290

Your question is a little hard to understand, but I think the issue you're having is down to not understanding how the request pipeline works. Your PageModel here is instantiated with every request and disposed at the end of said request, when the response is returned. When you make a new request, you have a brand new instance, so anything you previously set to a property like Inputs here is as if it never happened. If you're trying to persist something between requests, you actually need to persist it somewhere. That could be as simple as using Session or actually saving something to a database or other store.

Upvotes: 4

Related Questions