我在控制器中有一个方法可以改变用户的角色。完成后,我试图在 Controller 中的方法完成后将用户保留在当前 URL 中。我目前通过发送 return Redirect("/Profile/Index/" + id);
来执行此操作,这是我正在执行此方法的页面。
这工作得很好,但我想知道这是否是最佳实践,或者是否存在一种方法来简单地将用户保持在页面内。
Index.cshtml
<form method="POST" asp-area="" asp-controller="Profile" asp-action="Demote" asp-route-id="@Model.UserId">
<button type="submit" class="btn btn-outline-danger fs-5 mt-3">Demote User</button>
</form>
ProfileController.cs
[HttpPost]
public IActionResult Promote(string id)
{
var user = _nemesysRepository.GetUserById(id);
_userManager.RemoveFromRolesAsync(user, _userManager.GetRolesAsync(_nemesysRepository.GetUserById(id)).Result).Wait();
_userManager.AddToRoleAsync(user, "Investigator");
return Redirect("/Profile/Index/" + id); //===NEEDS TO REDIRECT TO BACK===
}
答案 0 :(得分:0)
最好使用更适合此类场景的内置RedirectToAction()
方法:
return RedirectToAction(null, new { id });
通过仅传递新的 routeValues
,将自动保留当前的 action
和 controller
。
答案 1 :(得分:-2)
只需返回 View();将返回相同的当前页面。