How to add a event to a button using Razor?
Solution 1
In razor pages, you could use javascript and @functions
directive 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
}
}
Related videos on Youtube
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, 2022Comments
-
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 almost 4 yearsYou can if you use a Blazor project and write all of your front-end code in C#.
-
NetoTI almost 4 yearsSeens 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 almost 4 yearsNo, without using Blazor, there is no way to handle client-side events using C# or Razor, without involving forms or JavaScript.
-
-
poke almost 4 yearsThis solution requires Blazor which OP says they cannot use.
-
poke almost 4 yearsThis solution requires Blazor which OP says they cannot use.