首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何正确地重定向到ASP.NET核心剃刀页面中的同一页面?

如何正确地重定向到ASP.NET核心剃刀页面中的同一页面?
EN

Stack Overflow用户
提问于 2021-11-07 08:02:00
回答 1查看 316关注 0票数 0

下面是一个简化的代码隐藏:

代码语言:javascript
复制
[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页面:

代码语言:javascript
复制
@page "/product/{id}"
@model Product

<div>
    @Model.Title
</div>

我被困在正确的重定向用户上。如果我没有返回IActionResult,那么我的Redirect("/login")就不能工作,并且我会得到@Model.Title的空引用异常。

如果我使用IActionResult,那么我的Redirect("/login")可以工作,但在用户登录并将产品添加到收藏夹后,我将用户返回到同一页面的代码失败,OneGet也不会被调用。

EN

回答 1

Stack Overflow用户

发布于 2021-11-07 08:31:14

在Razor中,您可以使用RedirectToPage()

假设类被命名为IndexModel

代码语言:javascript
复制
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操作,请执行以下操作:

代码语言:javascript
复制
public void OnGet(int productId)
{
    Product = ProductService.Get(productId)
}

在你看来:

代码语言:javascript
复制
@page "/product/{productId}"

在OnPost中

代码语言:javascript
复制
return RedirectToPage("Index", new { productId = ProductId});
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69870684

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档