Ajax in ASP.NET Core MVC 5

On the Visual Studio, select Create a new project from Get Started

Select ASP.NET Core Web Application




Input Project Name and select Location for new project

Select ASP.NET Core 5.0 Version and select ASP.NET Core Empty Template. Click Create 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;
using Microsoft.Extensions.Hosting;

namespace LearnASPNETCoreMVC5
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
        }

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

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Demo}/{action=Index}/{id?}");
            });
        }
    }
}

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

Create new class named Product.cs as below:

namespace LearnASPNETCoreMVC5.Models
{
    public class Product
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string Photo { get; set; }
    }
}




Create new folder named Controllers. In this folder, create new controller named DemoController.cs as below:

using LearnASPNETCoreMVC5.Models;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

namespace LearnASPNETCoreMVC5.Controllers
{
    [Route("demo")]
    public class DemoController : Controller
    {
        [Route("")]
        [Route("index")]
        [Route("~/")]
        public IActionResult Index()
        {
            return View();
        }

        [Route("demo1")]
        public ContentResult Demo1()
        {
            return Content("Hello", "text/plain");
        }

        [Route("demo2/{fullName}")]
        public ContentResult Demo2(string fullName)
        {
            return Content("Hello " + fullName, "text/plain");
        }

        [Route("demo3")]
        public IActionResult Demo3()
        {
            var product = new Product()
            {
                Id = "p01",
                Name = "name 1",
                Price = 123
            };
            return new JsonResult(product);
        }

        [Route("demo4")]
        public IActionResult Demo4()
        {
            var products = new List<Product>()
            {
                new Product() {
                    Id = "p01",
                    Name = "name 1",
                    Price = 123
                },
                new Product() {
                    Id = "p02",
                    Name = "name 2",
                    Price = 456
                },
                new Product() {
                    Id = "p03",
                    Name = "name 3",
                    Price = 789
                }
            };
            return new JsonResult(products);
        }

    }
}




Create new folder named Views. In this folder, create new folder named Demo. Create new view named Index.cshtml as below:

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {

            $('#buttonDemo1').click(function () {
                $.ajax({
                    type: 'GET',
                    url: '/demo/demo1',
                    success: function (result) {
                        $('#result1').html(result);
                    }
                });
            });

            $('#buttonDemo2').click(function () {
                var fullName = $('#fullName').val();
                $.ajax({
                    type: 'GET',
                    url: '/demo/demo2/' + fullName,
                    success: function (result) {
                        $('#result2').html(result);
                    }
                });
            });

            $('#buttonDemo3').click(function () {
                $.ajax({
                    type: 'GET',
                    url: '/demo/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',
                    url: '/demo/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>
        <input type="button" value="Demo 1" id="buttonDemo1" />
        <br />
        <span id="result1"></span>
    </fieldset>

    <fieldset>
        <legend>Demo 2</legend>
        Full Name <input type="text" id="fullName" />
        <input type="button" value="Demo 2" id="buttonDemo2" />
        <br />
        <span id="result2"></span>
    </fieldset>

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

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

</body>
</html>




Access Index action in Demo controller with following url: http://localhost:48982/Demo/Index

Output