Search code examples
c#asp.netasp.net-corerazor-pages

How to call a Razor page C# method from Layout.cshtml


I have a .Net6 razor page application, there I have a page called Index.chshtml and the corresponding code behind file Index.chshtml.cs

Now I have a method in the Index.chshtml.cs file called OnPostProfile() which I can call from the index.cshtml page like this:

// index.cshtml code

 <form asp-page-handler="profile" method="post">
    <button class="btn btn-default">Profile</button>
</form> 


// code behind  (index.cshtml.cs)

public void OnPostProfile()
{
   // do stuff
}

This works fine, however I want to call this codebehind method from _layout.cshtml file (Navbar link) as this method will be called from multiple screens.

Here is what I have tried (these are not working)

 <li class="nav-item">
      <a class="nav-link text-dark" asp-area="" asp-page="/Index/profile">Profile</a>
  </li> 

 <li class="nav-item">
      <a class="nav-link text-dark" asp-area="" asp-page-handler="/Index/profile">Profile</a>
  </li> 

How can I call this C# method from _layout.cshtml (Navbar)?


Solution

  • You can use below code to implement it.

    <li class="nav-item">
        <form id="profileForm" asp-page="/Index" asp-page-handler="profile" method="post" class="form-inline" style="display:none;">
        </form>
        <a href="javascript:void(0);" onclick="document.getElementById('profileForm').submit();" class="nav-link text-dark">Profile</a>
    </li>
    

    Here is my test result and will share the detailed code later.

    enter image description here

    _Layout.cshtml

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>@ViewData["Title"] - WebApplication1</title>
        <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
        <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
        <link rel="stylesheet" href="~/WebApplication1.styles.css" asp-append-version="true" />
    </head>
    <body>
        <header>
            <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
                <div class="container">
                    <a class="navbar-brand" asp-area="" asp-page="/Index">WebApplication1</a>
                    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                            aria-expanded="false" aria-label="Toggle navigation">
                        <span class="navbar-toggler-icon"></span>
                    </button>
                    <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
                        <ul class="navbar-nav flex-grow-1">
                            <li class="nav-item">
                                <a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Privacy</a>
                            </li>
                            <li class="nav-item">
                                <form id="profileForm" asp-page="/Index" asp-page-handler="profile" method="post" class="form-inline" style="display:none;">
                                </form>
                                <a href="javascript:void(0);" onclick="document.getElementById('profileForm').submit();" class="nav-link text-dark">Profile</a>
                            </li>
                        </ul>
                    </div>
                </div>
            </nav>
        </header>
        <div class="container">
            <main role="main" class="pb-3">
                @RenderBody()
            </main>
        </div>
    
        <footer class="border-top footer text-muted">
            <div class="container">
                &copy; 2023 - WebApplication1 - <a asp-area="" asp-page="/Privacy">Privacy</a>
            </div>
        </footer>
    
        <script src="~/lib/jquery/dist/jquery.min.js"></script>
        <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
        <script src="~/js/site.js" asp-append-version="true"></script>
    
        @await RenderSectionAsync("Scripts", required: false)
    </body>
    </html>
    

    Index.cshtml

    @page
    @model IndexModel
    @{
        ViewData["Title"] = "Home page";
    }
    
    <div class="text-center">
        <h1 class="display-4">Welcome</h1>
        <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
    </div>
    <form asp-page-handler="profile" method="post">
        <button class="btn btn-default">Profile</button>
    </form>
    

    Index.cshtml.cs

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    
    namespace WebApplication1.Pages
    {
        public class IndexModel : PageModel
        {
            private readonly ILogger<IndexModel> _logger;
    
            public IndexModel(ILogger<IndexModel> logger)
            {
                _logger = logger;
            }
    
            public void OnGet()
            {
    
            }
            public void OnPostProfile()
            {
                Console.WriteLine("Profile handler called!");
    
            }
        }
    }