Search code examples
asp.net-corerazor-pages

Count the number of times the link is clicked (ASP.NET Core razor page asp-page-handler)


Who can help me? I have a link that points to another page. And I want to count the number of times this link is clicked and store it in my SQL Server database. My page is an ASP.NET Core razor page. I have a column variabelSearch in my database table and I have to increase this column by +1 every time I click on the link.

Public void OnGetLeagueAsync(Guid? varLgPlayerId)
{
    HttpContext.Session.SetString("SessionLgPlayerId", varLgPlayerId.ToString());
    Response.Redirect("/LeaguePlayerDetails"); 

    variabelSearch++;
}

<td>
    <a asp-page-handler="League" asp-route-varLgPlayerId="@itemP.id">@itemP.naam</a>
</td>

Solution

  • Firstly, you need have a table which contains property variabelSearch:

    public class SearchCount
    {
        // Other properties...
        public int VariabelSearch { get; set; }
    }
    

    Then in your backend code:

    public async Task OnGetLeagueAsync(Guid? varLgPlayerId)
    {
        HttpContext.Session.SetString("SessionLgPlayerId", varLgPlayerId.ToString());
    
        // Assuming _context is your database context, 
        //and you have a known ID for the row you're updating. e.g. your passing varLgPlayerId
        var searchCount = await _context.SearchCounts.FindAsync(knownId);
        if (searchCount != null)
        {
            searchCount.VariabelSearch += 1;
            await _context.SaveChangesAsync();
        }
    
        Response.Redirect("/LeaguePlayerDetails");
    }