How to call function in razor .cs using ajax?

mc 3,681 Reputation points
2022-08-24T06:31:04.377+00:00

In razor there is a OnGet,OnPostAsync

I add a OnPostDeleteAsync(int id)

how to post to it using ajax?

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

Accepted answer
  1. Xinran Shen - MSFT 2,091 Reputation points
    2022-08-24T08:07:48.583+00:00

    Hi, @mc ,
    If you want to access method in Razor Page by ajax, You just need to add ?handler=(method name without OnPost or OnGet) in Url like:

    type: "POST",  
    url: '/Index?handler=Delete',   
    headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },  
    

    Attention: You also need to check If the form contains RequestVerificationToken (contains by default), If the from doesn't contains that token, You need to add:

    @Html.AntiForgeryToken()  
    

    In your form.

    -----------------------------------------------------------------------------------------------------------------

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Xinran Shen


1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 56,026 Reputation points
    2022-08-24T16:28:44.653+00:00

    to call OnPostDeleteAsync(int id) you use the DELETE method

    // native  
    var url = "/PageName?id=" + id;  
    var rs = await fetch(url, {  
        method: "DELETE"  
    });  
      
      
    //jquery  
    var rs = await $.ajax({  
           type: "DELETE",  
           url: "/PageName",  
           data: {id : id}   
     });  
      
      
    
    1 person found this answer helpful.