点击按钮后从一个Razor页面导航到另一个Razor页面?

4
当单击按钮时,从Index.cshtml导航到Inventory.cshtml,是否有更好的方法进行导航?以下是我目前使用的解决方案,虽然它有效,但我不确定这是否是正确的方式。参考资料:https://www.jetbrains.com/dotnet/guide/tutorials/basics/razor-pages/

Index.cshtml:

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

<!--Page redirect-->
<form method="post" asp-page="Index">
   <button type="submit" class="btn btn-cta">View Inventory</button>
</form>

Index.cshtml.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace TheInventory.Pages
{
    public class IndexModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;

        public IndexModel(ILogger<IndexModel> logger)
        {
            _logger = logger;
        }

        public void OnGet()
        {

        }

        //Page redirect on button form submit
        public IActionResult OnPost()
        {
            return RedirectToPage("Inventory");
        }
    }
}

Inventory.cshtml

@page
@model TheInventory.Pages.InventoryModel
@{
    ViewData["Title"] = "Inventory";
}

<h1>@ViewData["Title"]</h1>

<p>This is the Inventory Page</p>

你可以在客户端使用JavaScript来完成这个操作。同时,创建一个锚点a并设置asp-controller和asp-action,然后进行重定向。或者创建一个锚点a并硬编码路径。请参考以下链接:https://learn.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/built-in/anchor-tag-helper?view=aspnetcore-6.0 - user123456
@user123456 感谢您的回复。我会查看提供的链接并尝试使用您提供的解决方案。 - Dylan
1个回答

5
为了解决我的问题,我在Razor Pages中使用了asp-page属性,并将锚点标签的href属性值设置为特定页面。
参考链接:asp.net core anchor tag helper - Razor pages
<a asp-page="/PageExample">Page Example</a>

我将锚点元素包裹在按钮元素中,当点击按钮时,就可以导航到指定的页面。

以下是我的代码片段:

<button type="button" class="btn btn-cta"><a asp-page="/Inventory">Manage Inventory</a></button>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接