How to call a code behind method in razor pages ?

Butachan 21 Reputation points
2023-02-07T14:48:55.5866667+00:00

Hello I have razor form . When the user cancel , I need to execute the following method.



I have tried the following with no success:

  1. <a type="button" href='@Url.Action("Myform","CancelButton_Click")'...>
  2. and then <button id="CancelButton" type="button" onclick="CancelButton_Click"> to attempt to call a method:
   protected void CancelForm_Submit(object sender, EventArgs e)
  1. <button type="button" asp-page-handler="BacktoTableau">
    1. And Ajax :
   
   $.ajax({
   
           type: "POST",
           url: "/MyForm?handler=BacktoTableau",
           function(result) {
               alert(result);
           }
   

which is the only one I could get to enter inside the Code behind, but then the

   Response.Redirect("/index_bis");

doesn't redirect, and the rest of the js execute

I don't use MVC, so please forget about controller or view

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,150 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Butachan 21 Reputation points
    2023-02-07T16:01:19.0066667+00:00

    I have tried many other codes including asp-page-handler, form submit, etc, but the button execute the onget method instead of the cancel method.

    For now with the ajax I use window.location.replace('/index_bis'); which works but I am not a fan.

    I am still opened to more scalable solution.

    I don't know why is it so hard to just call a method in the code behind related to the current razor view

    0 comments No comments

  2. Bruce (SqlWork.com) 55,366 Reputation points
    2023-02-07T17:05:14.2566667+00:00

    you use handler methods:

    https://www.learnrazorpages.com/razor-pages/handler-methods

        <form asp-page-handler="cancel" method="post">
            <button class="btn btn-default">Cancel</button>
        </form>  
    
    public void OnPostCancel()
    {
       // do something
    }   
    
    0 comments No comments