How to handle Ajax requests in ASP.NET Core Razor Pages?

Posted by Anuraj on Tuesday, October 10, 2017

ASP.NET Core Razor Pages

This post is about handling Ajax requests in ASP.NET Core Razor Pages. Razor Pages is a new feature of ASP.NET Core MVC that makes coding page-focused scenarios easier and more productive.

I already posted a blog post about jQuery Unobtrusive Ajax Helpers in ASP.NET Core, which you can use it in Razor Pages as well. But most of those helpers are for POST / PUT requests, what if you want to load something in async way like cascading dropdown lists. So you might required to use jQuery ajax methods ($.get or $.getJson). OnGetCountries method returns list of countries.

$.getJSON("/Index/OnGetCountries", function(data){
    //Do something with result data
});

But if you tried to access a Razor Page method via standard routing, it might not work.

Ajax Request failed

If you’re creating a new method in Razor Pages other than default OnGet or OnPost methods, you are able to access it via Handlers. So you need to use the handler context in the ajax request to work. So if you are using OnGetCountries method, you need to send the ajax request like this.

$.getJSON("/Index?handler=Countries", function(data){
    //Do something with result data
});

Ajax Request failed

Now it is started working. You can use the same method for post requests as well.

Happy Programming :)


Similar Posts


Did you like this article? Share it with your friends

Facebook Twitter Google+ LinkedIn Reddit StumbleUpon



Subscribe


Copyright © 2017 - Anuraj P. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Hosted with ❤ by GitHub