下面是一个简化的代码隐藏:
[BindProperty(SupportsGet = true)]
public int ProductId { get; set; }
public Product Product { get; set; }
public void OnGet()
{
Product = ProductService.Get(ProductId)
}
public IActionResult OnPost()
{
if (!User.Identity.IsAuthenticated)
{
retrun Redirect("/login");
}
// Add product to user favorite list
// Then how to redirect properly to the same page?
// return Redirect("/product") is not working
// Calling OnGet() does not work
}下面是相应的简化版Razor页面:
@page "/product/{id}"
@model Product
<div>
@Model.Title
</div>我被困在正确的重定向用户上。如果我没有返回IActionResult,那么我的Redirect("/login")就不能工作,并且我会得到@Model.Title的空引用异常。
如果我使用IActionResult,那么我的Redirect("/login")可以工作,但在用户登录并将产品添加到收藏夹后,我将用户返回到同一页面的代码失败,OneGet也不会被调用。
发布于 2021-11-07 08:31:14
在Razor中,您可以使用RedirectToPage()
假设类被命名为IndexModel
public class IndexModel: PageModel
{
public IActionResult OnPost()
{
if (!User.Identity.IsAuthenticated)
{
return Redirect("/login");
}
// Add product to user favorite list
// Then how to redirect properly to the same page?
// return Redirect("/product") is not working
// Calling OnGet() does not work
return RedirectToPage("Index");
}
}注意:您拼写错了return。在你的代码中写着retrun
更新您想要遵循PRG模型: after a Post You Re edirect to a Get
要将参数传递回OnGet操作,请执行以下操作:
public void OnGet(int productId)
{
Product = ProductService.Get(productId)
}在你看来:
@page "/product/{productId}"在OnPost中
return RedirectToPage("Index", new { productId = ProductId});https://stackoverflow.com/questions/69870684
复制相似问题