I am using ASP Net Core, and I created a project with Razor Pages.
I have a page which lists products associated with the current user, and he can add a new product.
After the OnPost method is called, I want to refresh the page so that it displays all the products of the user without requesting the database again
Below is my current solution:
public async Task OnGet()
{
var currentUser = await GetCurrentUser();
if (currentUser != null)
Products = await _dbContext.Products.Where(x => x.AtpUserId == currentUser.Id).ToListAsync();
}
public async Task OnPost(Product product)
{
var currentUser = await GetCurrentUser();
if (currentUser != null)
{
product.UserId = currentUser.Id;
product.Currency = "USD";
await _dbContext.Products.AddAsync(product);
await _dbContext.SaveChangesAsync();
Products = await _dbContext.Products.Where(x => x.UserId == currentUser.Id).ToListAsync(); // can I avoid this ?
}
}
I don't find how I achieve the same result without the last line which reloads the data from the database.
- I looked at some examples but examples from the scaffold pages all use an intermediate
Createpage, and then redirect to theIndexpage. I want the user to be able to create from the Index page - I tried to replace the last line of the
OnPostmethod by a call toRedirectToPage("Index");but the methodOnGetis not called again and the table containing the products is empty on refresh. Why?