What I’m trying to do is to call function by a button.
i'll leave you with a simple code that doesn't work!:
@{
protected void print()
{
@<p>WELCOME!</p>
}
}
<form>
<button onclick="print" value="CLICK ME"/>
</form>
any idea on how to accomplish what im trying to do in the code above?
NOTE: IM NOT USING MVC
You can't do it like this.It is not
ASP.NET WebForms
.So if you want to Execute a C# function on Button click in Razor, you
mustcould create aController
,then when user clicks a button youmustcan call a javascript function and it sends an ajax request to your controller then get the data (if there is data) and display it.Update: Here is an alternative simple sample about how to do this:
In your Controller Add this Method:
And in your View (HTML):
JavaScript:
And don't forget to import jQuery library:
PS: I assume your Controller name is HomeController, you must change the url if it has different name:
I know this is an old question, but this is the first result on google when you look up how to run an
OnClick
method in ASP Razor, and I think there is a better way to do this than the currently accepted answer. I don't know if this is new as of the writing of the original answer, but I do think it is the best way to handle this behavior because it doesn't require hand-writing of AJAX or JavaScript methods.For those coming from Web Forms into ASP Razor, perhaps the best (and easiest) way to recreate that type of behavior is to use a Handler Method. Handler Methods are appended to the Get and Post methods, and can be run using forms generated by ASP Razor.
By default, your cshtml.cs page will have a function which looks like this:
Sometimes though, you want to do something specific depending on what exactly caused the post. This is where you can implement Handler Methods.
If you then want to use the button method, you simply create an ASP Button that indicates its handler method.
This will tell razor pages to add a reference to the Button Handler Method in the querystring of the resulting button, like so.
A visit to that will tell Razor to use the named handler method. As long as the name of the handler matches the name of the function and HTTP Method, it will run the function.
Your code would look like this:
Don't forget, this will only call the OnPostPrint method. If you need to run stuff every time you post, it needs to be in that method too. Probably best to break those tasks out into a separate function, and then call that from within the post methods. Makes it easier to maintain.
For more info on Method Handlers, including how to add variables to them, check out Mikes DotNetting! He did a great job of explaining this thoroughly, and I feel I learned a lot from his article.
https://www.mikesdotnetting.com/article/308/razor-pages-understanding-handler-methods