How to add a event to a button using Razor?

14,887

Solution 1

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/

Solution 2

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 
 }
}
Share:
14,887

Related videos on Youtube

NetoTI
Author by

NetoTI

I am a Software Engineering Student and a hobby Developer at free hours, as well a developer in a home family business. I am interested in fullStack Development as well multiplatform development and adept of .Net Framework Tecnologies

Updated on June 04, 2022

Comments

  • NetoTI
    NetoTI almost 2 years

    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"/>
    
    • Daniel Mann
      Daniel Mann almost 4 years
      You can if you use a Blazor project and write all of your front-end code in C#.
    • NetoTI
      NetoTI almost 4 years
      Seens like a Blazor a good ideia indeed, but i can't port the solution right now, actually i am limited to Razor Pages Asp.net core
    • poke
      poke almost 4 years
      No, without using Blazor, there is no way to handle client-side events using C# or Razor, without involving forms or JavaScript.
  • poke
    poke almost 4 years
    This solution requires Blazor which OP says they cannot use.
  • poke
    poke almost 4 years
    This solution requires Blazor which OP says they cannot use.