Friday, March 29, 2024
HomeC#AJAX Calls in ASP.NET Core Razor Pages

AJAX Calls in ASP.NET Core Razor Pages


Razor Pages is a brand new programming mannequin in ASP.NET Core.

As an alternative of the MVC mannequin, this programming mannequin relies on web page routes. Every web page is separated into two information: one for the backend and the opposite one for the frontend.

Razor Pages solely works with GET and POST strategies. A web page will comprise two strategies: OnGet and OnPost.

Deal with AJAX Calls in Razor Pages

With a view to deal with AJAX calls in Razor Pages, you have to use named handler strategies:

[IgnoreAntiforgeryToken]
public class IndexModel : PageModel
{
    personal 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.Subsequent(1000);
        RandomWinner = $"Participant {random.Subsequent(1, 4)}";
    }

    public IActionResult OnPostRandomNumber([FromBody]RandomNumberDTO randomNumber)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest("Invalid mannequin");
        }
        Random random = new Random();
        int quantity= random.Subsequent(randomNumber.Min, randomNumber.Max);
        return new JsonResult(quantity);
    }
}

Within the above instance, I’ve renamed the OnPost technique into OnPostRandomNumber. After this variation, I’ll modify the URL of the AJAX request within the JQuery:

operate RandomNumber() {
    var min = $("#Min").val();
    var max = $("#Max").val();
    $.ajax({
        kind: 'POST',
        url: "/?handler=RandomNumber",
        information: JSON.stringify({ Min: min, Max: max }),
        contentType: "software/json",
        dataType: "json",
    }).performed(operate(information) {
        $("#lblRandomNumber").textual content(information);
    })
        .fail(operate(error) {
            $("#lblRandomNumber").textual content(error.responseText);
        });
}

Be sure you use the attribute [IgnoreAntiforgeryToken]. In the event you don’t use this attribute, ASP.NET will take a look at the header RequestVerificationToken of the request. If the worth will not be the identical as what the server has, then an error is acquired.

How one can use the anti-forgery token in AJAX calls

First, you have to embrace the token in your web page. Check out the supply code of your web page. When you have a type tag with publish attribute, then ASP.NET will robotically add this token for you. In any other case, you have to add by calling this helper:

@Html.AntiForgeryToken()

Second, you have to embrace this token within the header of the AJAX request:

operate RandomNumber() {
    var min = $("#Min").val();
    var max = $("#Max").val();
    $.ajax({
        kind: 'POST',
        url: "/?handler=RandomNumber",
        information: JSON.stringify({ Min: min, Max: max }),
        contentType: "software/json",
        dataType: "json",
        headers: {
       RequestVerificationToken: 
           $('enter:hidden[name="__RequestVerificationToken"]').val()
       }
    }).performed(operate(information) {
        $("#lblRandomNumber").textual content(information);
    })
        .fail(operate(error) {
            $("#lblRandomNumber").textual content(error.responseText);
        });
}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments