Razor Pages is a new programming model in ASP.NET Core.
Instead of the MVC model, this programming model is based on page routes. Each page is separated into two files: one for the backend and the other one for the frontend.
Razor Pages only works with GET and POST methods. A page will contain two methods: OnGet
and OnPost.
Handle AJAX Calls in Razor Pages
In order to handle AJAX calls in Razor Pages, you must use named handler methods:
[IgnoreAntiforgeryToken] public class IndexModel : PageModel { private readonly ILogger<IndexModel> _logger; public IndexModel(ILogger<IndexModel> logger) { _logger = logger; } public int RandomNumber { get; set; } public string RandomWinner { get; set; } public void OnGet() { Random random = new Random(); RandomNumber = random.Next(1000); RandomWinner = $"Player {random.Next(1, 4)}"; } public IActionResult OnPostRandomNumber([FromBody]RandomNumberDTO randomNumber) { if (!ModelState.IsValid) { return BadRequest("Invalid model"); } Random random = new Random(); int number= random.Next(randomNumber.Min, randomNumber.Max); return new JsonResult(number); } }
In the above example, I have renamed the OnPost method into OnPostRandomNumber. After this change, I will modify the URL of the AJAX request in the JQuery:
function RandomNumber() { var min = $("#Min").val(); var max = $("#Max").val(); $.ajax({ type: 'POST', url: "/?handler=RandomNumber", data: JSON.stringify({ Min: min, Max: max }), contentType: "application/json", dataType: "json", }).done(function(data) { $("#lblRandomNumber").text(data); }) .fail(function(error) { $("#lblRandomNumber").text(error.responseText); }); }
Make sure you use the attribute [IgnoreAntiforgeryToken]
. If you don’t use this attribute, ASP.NET will look at the header RequestVerificationToken
of the request. If the value is not the same as what the server has, then an error is received.
How to use the anti-forgery token in AJAX calls
First, you must include the token on your page. Take a look at the source code of your page. If you have a form tag with post attribute, then ASP.NET will automatically add this token for you. Otherwise, you must add by calling this helper:
@Html.AntiForgeryToken()
Second, you must include this token in the header of the AJAX request:
function RandomNumber() { var min = $("#Min").val(); var max = $("#Max").val(); $.ajax({ type: 'POST', url: "/?handler=RandomNumber", data: JSON.stringify({ Min: min, Max: max }), contentType: "application/json", dataType: "json", headers: { RequestVerificationToken: $('input:hidden[name="__RequestVerificationToken"]').val() } }).done(function(data) { $("#lblRandomNumber").text(data); }) .fail(function(error) { $("#lblRandomNumber").text(error.responseText); }); }