I have a razor page with a List model that iterates over the list and displays model data. I have a button called "Delete" that deletes the item from the database based on the id. This part works ok. After deleting an item, I would like to stay on the same page with updated model list. How do I accomplish this? Right now, I "return Page()" from the understanding that this just refreshes the page. This just returns an empty page with no data in it.
UserList.cshtml:
@page
@model UserListModel
@{
ViewData["Title"] = "Index";
Layout = "~/Pages/Shared/_Layout.cshtml";
}
<h1>User Roles</h1>
<table >
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@foreach (var user in Model.UsersListModel)
{
<tr>
<td>@user.FirstName</td>
<td>@user.LastName</td>
<td>@user.Email</td>
<td>
<form method="post">
<input type="submit" asp-page-handler="Delete" asp-route-userId="@user.Id" value="Delete User" onclick="return confirm('Are you sure you want to delete the user?');"/>
</form>
</td>
</tr>
}
</tbody>
</table>
UserList.cshtml.cs:
public List<UserViewModel> UsersListModel { get; private set; } = new List<UserViewModel>();
public async Task OnGetAsync()
{
var users = await _userService.GetUsers.ToListAsync();
var userViewModel = new List<UserViewModel>();
foreach (ApplicationUser user in users)
{
var thisViewModel = new UserViewModel();
thisViewModel.UserId = user.Id;
thisViewModel.Email = user.Email;
thisViewModel.FirstName = user.FirstName;
thisViewModel.LastName = user.LastName;
userModel.Add(thisViewModel);
}
UsersListModel = userViewModel;
}
public async Task<IActionResult> OnPostDelete(string userId)
{
var result = await _userService.Delete(userId);
if (!result.Succeeded)
{
throw new InvalidOperationException($"Unexpected error occurred deleting user with ID '{userId}'.");
}
return Page(); // I would like to stay on the same page with the updated list of users.
}
CodePudding user response:
You cannot return Page()
directly at the end of the Post method, because the Post method execution ends you are not getting data from the database.
You can call back your Get method:
public async Task<IActionResult> OnPostDelete(string userId)
{
var result = await _userService.Delete(userId);
if (!result.Succeeded)
{
throw new InvalidOperationException($"Unexpected error occurred deleting user with ID '{userId}'.");
}
return RedirectToPage("./UserList");
}