Skip to content Skip to sidebar Skip to footer

Calling A C# Function By A Html Button

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() { @

WELCOME!

Solution 1:

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:

publicasync Task OnPostAsync()
{
    <Do Post Stuff Here>
}

Sometimes though, you want to do something specific depending on what exactly caused the post. This is where you can implement Handler Methods.

publicasync Task OnPostButton()
{
    <Do button stuff here>
}

If you then want to use the button method, you simply create an ASP Button that indicates its handler method.

<formasp-page-handler="button"method="post"><buttonclass="btn btn-default">Button</button></form>

This will tell razor pages to add a reference to the Button Handler Method in the querystring of the resulting button, like so.

<formmethod="post"action="/page?handler=button">

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:

@{
    protectedvoidprint()
    { 
        @<p>WELCOME!</p>
    }

    publicasync Task OnPostPrint()
    {
        print();
    }
}

<form asp-page-handler="Print" method="post">
   <button class="btn btn-default">CLICK ME</button>
</form>

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

Solution 2:

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 must could create a Controller,then when user clicks a button you must can 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:

public ActionResult GetMessage()
    {
        string message = "Welcome";
        returnnew JsonResult {Data = message,JsonRequestBehavior = JsonRequestBehavior.AllowGet};
    }

And in your View (HTML):

<inputtype="button"onclick="GetMessage()"value="Get Message"/><p></p>

JavaScript:

functionGetMessage() {
        $.get("/Home/GetMessage", function (data) {
            $("p").html(data);
        });
    }

And don't forget to import jQuery library:

<scriptsrc="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

PS: I assume your Controller name is HomeController, you must change the url if it has different name:

$.get("/{Controller-Name}/{Action-Name}", ...)

Solution 3:

<input type="button" id="button" value="click me" />

@{
    stringMyFunction()
    {
        return"Hello Razor";
    }
}

@sectionScripts
{
    <scripttype="text/javascript">document.addEventListener("DOMContentLoaded", function () {
            var button = document.getElementById('button');
            button.addEventListener('click', function () {
                var test = "@MyFunction()";
                console.log(test);
             });
        });
    </script>
}

Post a Comment for "Calling A C# Function By A Html Button"