Ajax in ASP.NET Core Razor Pages

On the Visual Studio, create new ASP.NET Core Web Application project

Select Empty Template

Click Ok button to Finish




Open Startup.cs file and add new configurations as below:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;

namespace LearnASPNETCoreRazorPagesWithRealApps
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }
    }
}

Select Views folder and right click to select Add\New Item Menu

Select Web\ASP.NET in left side. Select Razor View Imports item and click Add button to Finish

In _ViewImports.cshtml file and TagHelpers library as below:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers




Create new folder named Models. In Models folder, create new entity class as below:

Create new class named Product.cs as below:

namespace LearnASPNETCoreRazorPagesWithRealApps.Models
{
    public class Product
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public double Price { get; set; }
    }
}

Create new folder named Pages. In this folder, create new Razor Page named Index as below:

using System.Collections.Generic;
using LearnASPNETCoreRazorPagesWithRealApps.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace LearnASPNETCoreRazorPagesWithRealApps.Pages
{
    public class IndexModel : PageModel
    {
        public void OnGet()
        {
        }

        public IActionResult OnGetDemo1()
        {
            return new JsonResult("Hello");
        }

        public IActionResult OnGetDemo2(string fullName)
        {
            return new JsonResult("Hi " + fullName);
        }

        public IActionResult OnGetDemo3()
        {
            var product = new Product
            {
                Id = "p01",
                Name = "name 1",
                Price = 4.5
            };
            return new JsonResult(product);
        }

        public IActionResult OnGetDemo4()
        {
            var products = new List<Product>
            {
                new Product {
                    Id = "p01",
                    Name = "name 1",
                    Price = 4.5
                },
                new Product {
                    Id = "p02",
                    Name = "name 2",
                    Price = 7
                },
                new Product {
                    Id = "p03",
                    Name = "name 3",
                    Price = 9
                }
            };
            return new JsonResult(products);
        }
    }
}




@page
@model LearnASPNETCoreRazorPagesWithRealApps.Pages.IndexModel

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="https://code.jquery.com/jquery-3.4.0.js"></script>
    <script>
        $(document).ready(function(){

            $('#buttonDemo1').click(function(){
                $.ajax({
                    type: 'GET',
                    url: '@Url.Page("index", "demo1")',
                    success: function (result) {
                        $('#result1').html(result);
                    }
                });
            });

            $('#buttonDemo2').click(function () {
                var fullName = $('#texboxFullName').val();
                $.ajax({
                    type: 'GET',
                    data: { fullName: fullName},
                    url: '@Url.Page("index", "demo2")',
                    success: function (result) {
                        $('#result2').html(result);
                    }
                });
            });

            $('#buttonDemo3').click(function () {
                $.ajax({
                    type: 'GET',
                    dataType: 'json',
                    contentType: 'application/json',
                    url: '@Url.Page("index", "demo3")',
                    success: function (result) {
                        var s = 'Id: ' + result.id;
                        s += '<br>Name: ' + result.name;
                        s += '<br>Price: ' + result.price;
                        $('#result3').html(s);
                    }
                });
            });

            $('#buttonDemo4').click(function () {
                $.ajax({
                    type: 'GET',
                    dataType: 'json',
                    contentType: 'application/json',
                    url: '@Url.Page("index", "demo4")',
                    success: function (result) {
                        var s = '';
                        for (var i = 0; i < result.length; i++) {
                            s += '<br>Id: ' + result[i].id;
                            s += '<br>Name: ' + result[i].name;
                            s += '<br>Price: ' + result[i].price;
                            s += '<br>----------------------------';
                        }
                        $('#result4').html(s);
                    }
                });
            });

        });
    </script>
</head>
<body>

    <fieldset>
        <legend>Demo 1</legend>
        <form>
            <input type="button" value="Demo 1" id="buttonDemo1" />
            <br />
            <span id="result1"></span>
        </form>
    </fieldset>

    <fieldset>
        <legend>Demo 2</legend>
        <form>
            <input type="text" id="texboxFullName" />
            <input type="button" value="Demo 2" id="buttonDemo2" />
            <br />
            <span id="result2"></span>
        </form>
    </fieldset>

    <fieldset>
        <legend>Demo 3</legend>
        <form>
            <input type="button" value="Demo 3" id="buttonDemo3" />
            <br />
            <span id="result3"></span>
        </form>
    </fieldset>

    <fieldset>
        <legend>Demo 4</legend>
        <form>
            <input type="button" value="Demo 4" id="buttonDemo4" />
            <br />
            <span id="result4"></span>
        </form>
    </fieldset>

</body>
</html>




Open Index Razor Page with following url: http://localhost:1115