skip to Main Content

How can I link a button click to a method on Razor pages, am using ASP.NET Core 6?

I have this bit of code from a razor pages Test.cshtml

<Button>Do some stuff</Button>

and I want to link it to this method from Test.cshtml.cs

public void SomeStuff() { //Some C# code }

I know how to do it if it was a post form but is there any other way to invoke that method?

Trying to link a button click event from a cshtml razor pagee to a function in a cshtml.cs file

2

Answers


  1. Trying to link a button click event from a cshtml razor pagee to a
    function in a cshtml.cs file

    Can you use this way ?

    Wrap the anchor tag element in the button element and is able to navigate to the specified page method when the button was clicked.

    <button ><a asp-page-handler="SomeStuff" class="nav-link text-dark">Do some stuff</a></button>
    

    Index.cshtml.cs:

    public  void OnGetSomeStuff() { }
    
    Login or Signup to reply.
  2. can you try this way ?

    <Button id="ButtonID">Do some stuff</Button>
    
    <script>
    $("#ButtonID").click(function() {
    CallAjaxMethod("/Test/SomeStuff/").then(function (result) {
           // Your action after getting the response
        });
    });
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search