简体   繁体   中英

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

Here's a simplified code-behind:


[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
}

And here's the corresponding simplified Razor Page:

@page "/product/{id}"
@model Product

<div>
    @Model.Title
</div>

I'm stuck at properly redirecting user. If I don't return IActionResult then my Redirect("/login") does not work and I get null reference exception for @Model.Title .

If I use IActionResult then my Redirect("/login") works, but after user logins and adds product to favorites, my code on returning user to the same page fails and OneGet does not get called.

In Razor you would use RedirectToPage()

Suppose the class is named 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");
   }
}

note: you misspelled return . Is says retrun in you code

update You want to follow the PRG model: after a P ost you R edirect to a G et

to pass parameters back to the OnGet action doe this:

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

and in your view:

@page "/product/{productId}"

and in the OnPost

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM