簡體   English   中英

如何正確重定向到 ASP.NET Core Razor Pages 中的同一頁面?

[英]How to properly redirect to the same page in ASP.NET Core Razor Pages?

這是一個簡化的代碼隱藏:


[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不會被調用。

在 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模式:在P OST之后你[R edirect到G

要將參數傳遞回 OnGet 操作,請執行以下操作:

public void OnGet(int productId)
{
    Product = ProductService.Get(productId)
}

在您看來:

@page "/product/{productId}"

並在 OnPost

return RedirectToPage("Index", new { productId = ProductId});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM