Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my ASP.NET Razor Pages OnClick method not firing?

I have this Button in my Index.cshmtl

<button value="Search" name="Search" submit="Search" class="searchbutton" onclick="btnSearch_Click">Search</button>

this Button sends a post when clicked.

In my Index.cshtml.cs I have this boolean variable and function

private bool SearchButton;
protected void btnSearch_Click(object sender, EventArgs e)
{
    SearchButton = true;
}

So my problem is that, if I click the Button the code will never enter the btnSearch_Click function

like image 869
LionTheK1ng Avatar asked Oct 26 '25 01:10

LionTheK1ng


1 Answers

You can use a named handler method in Razor Pages to emulate a server-side event handler in Web Forms.

Here's a content page:

@page
@model RazorPagesDemo.Pages.HandlerDemoModel
@{
}
<p>@Model.Message</p>
<form asp-page-handler="Search" method="post">
    <input type="text" asp-for="SearchTerm" />
    <button class="btn btn-default">Search</button>
</form>

And here's the PageModel:

public class HandlerDemoModel : PageModel
{
    [BindProperty]
    public string SearchTerm { get; set; }
    public string Message { get; set; }

    public void OnPostSearch()
    {
        Message = $"You searched for {SearchTerm}";
    }
}

OnPostSearch is the equivalent to your btnSearch_Click method. You use the asp-page-handler attribute to wire your form up to execute that method. You can read more about Razor Pages handler methods here: https://www.learnrazorpages.com/razor-pages/handler-methods

like image 79
Mike Brind Avatar answered Oct 29 '25 18:10

Mike Brind