How to add a event to a button using Razor?

Viewed 20532

I am quite new to asp.net core development and I really don't know much of javascript, I am trying to know if there is some way to handle input events like OnClick() or OnChange() of Html inputs using only C#/Razor code without a form too and using only Razor Pages/MVC , Something Like this:

@{
    void RazorFunction()
     {
       //Do Stuff 
     }
}    
<button Onclick="RazorFunction"/>
4 Answers

In razor pages, you could use javascript and @functionsdirective which enables adding C# members (fields, properties, and methods) to the generated class:

@page
@model IndexModel

@functions{
    public string GetHello()
    {
        return "Hello";
    }
}

<button Onclick="RazorFunction()">Click</button>

@section Scripts
{
 <script>
    function RazorFunction() {
        $("button").html('@GetHello()');
    }

 </script>
} 

You could also refer to the below links to integrate ASP.NET Core Razor components and blazor into Razor Pages web app project:

https://docs.microsoft.com/en-us/aspnet/core/blazor/integrate-components?view=aspnetcore-3.1

https://andrewlock.net/replacing-ajax-calls-in-razor-pages-using-razor-components-and-blazor/

You can try something like this, by declaring the the @onclick and @onchange methods you could declare the methods in a code section below :

I had added some sample code for reference :

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

<input value="@currentCount" @onchange="chg" />

@code {
 int currentCount = 0;

 void IncrementCount()
 {
     currentCount++;
 }

 void chg(ChangeEventArgs e)
 {
     currentCount = 999;
 }
}

Very Simple just write the following html

<button @onclick="RazorFunction">Button</button>

You also need to change your code block as bellow

@code{

 void RazorFunction(MouseEventArgs e)
 {
   //Do Stuff 
 }
}

You can also do it like this in HTML:

@using (Html.BeginForm("FunctionName", "ControllerName"))
    {
        <button type="submit">TEXT</button>
    }

And in the controller add:

public ActionResult CheckLoginStatus()
    {
        //do stuff...
    }
Related