How to use AJAX with ASP.NET 6 Razor Pages

Last modified: March 03, 2022
Step 1

Create an ASP.NET Razor Page application.

createproject createproject createproject createproject createproject

Step 2

In the Index.cshtml.cs, create a method called "OnPostGetAjax" which take name as parameter and return a string. It is very import that we put [OnPost] in front of method to indicate it is POST AJAX request. It is Razor Page convention

public IActionResult OnPostGetAjax(string name) { return new JsonResult("Hello " + name); }
Step 3

@Html.AntiForgeryToken() is important, without passing an anti forgery token as a header, we can't call the method (OnPostGetAjax). The convention for url is PageName + "?handler=" + MethodName without OnPost or OnGet

@Html.AntiForgeryToken() <button type="button" id="callAjax" >Say Hello</button> @section Scripts { <script type="text/javascript"> $("#callAjax").click(function(){ $.ajax({ type: "POST", url: "/Index?handler=GetAjax", data:{"name": "Mark"}, contentType: 'application/x-www-form-urlencoded', dataType: "json", headers: { "RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val() }, success: function (msg) { console.log(msg); } }); }); </script> }