Search code examples
c#asp.net-coreasp.net-core-mvcrazor-pages

Navigate from one Razor page to another Razor page with button click?


Is there a better way to navigate from one Razor page to different Razor page when a button is clicked. I want to navigate from Index.cshtml to Inventory.cshtml when the button is clicked.

Below is the current solution that I have managed use that works, but I am not sure if this is correct way. Reference used: 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>

Solution

  • To solve my problem I used the asp-page attribute with Razor Pages and set an anchor tag's href attribute value to the specific page.

    Reference used: asp.net core anchor tag helper - Razor pages

    <a asp-page="/PageExample">Page Example</a>
    

    I wrapped the anchor tag element in the button element and was able to navigate to the specified page when the button was clicked.

    Here is an snippet of my code:

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