Home > Enterprise >  ASP.Net Core 6.0 OnGet handler not called when an anchor link is clicked
ASP.Net Core 6.0 OnGet handler not called when an anchor link is clicked

Time:07-11

I have the following html piece of code, which holds several links (This is one part of the Layout, which is used in my Razor pages):

<div >
    <ul>
        <li><a href="/About">About</a></li>
        <li><a href="/Privacy">Privacy Policy</a></li>
        <li><a href="/CookieList">Cookies List</a></li>
        <li><a href="/Terms">Terms of use</a></li>
    </ul>
</div>  

Then I have an OnGet handler for the About page:

public class AboutModel : PageModel
{
  private readonly DbDuhnjaContext mDataContext;

  public AboutModel(DbDuhnjaContext aDataContext)
  {
     mDataContext = aDataContext;
  }

  public void OnGet()
  {
     // Some code
  }
}

When I open the page by typing its path in the browser: https://mywebsite.com/About or refresh the page, it calls the OnGet method correctly. But if I click on the link it does not calls the method.

What am I missing here?

Best Regards

CodePudding user response:

If you create a new empty Razor Page, it creates the PageModel (cshtml.cs) and the Razor View (cshtml).

Your PageModel appears to be fine, but what is missing from the Razor View is what you'll see at the top of a new empty Razor Page. The @page directive (with no route in this case) and a @model attribute, which allows you to access the code behind in a strongly typed manner from the view.

Lastly, and most likely the cause of your links not using the AspNetCore routing, you should be using the asp-page Anchor TagHelper in your anchor tags.

@page
@model MyProjectName.Pages.AboutModel
<div >
    <ul>
        <li><a asp-page="/About">About</a></li>
        <li><a asp-page="/Privacy">Privacy Policy</a></li>
        <li><a asp-page="/CookieList">Cookies List</a></li>
        <li><a asp-page="/Terms">Terms of use</a></li>
    </ul>
</div> 

If you are not working from a File->New AspNetCore Web App you may also need to register the tag helpers in your Shared\_ViewImports.cshtml

// ...
@addTagHelper *,Microsoft.AspNetCore.Mvc.TagHelpers

CodePudding user response:

I am so sorry, it seems that the problem was on my side. The About page was served from the cache when I click on the link, and that cache contained a version where the OnGet handler was not implemented yet. After I cleared the cache it started working. Thank you

  • Related