LionTheK1ng
LionTheK1ng

Reputation: 33

Asp.Net Razor Pages OnClick 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

Upvotes: 3

Views: 3303

Answers (1)

Mike Brind
Mike Brind

Reputation: 30065

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

Upvotes: 2

Related Questions