find and solve || findandsolve.com
Please wait.....

Ajax in ASP.NET Core MVC and AJAX Tutorial

Ajax in ASP.NET Core MVC  and AJAX Tutorial

What is Ajax?

Ajax is a client-side script that communicates to and from a server without interfering with the display and behavior of the existing page. Ajax stands for Asynchronous JavaScript and XML. Ajax is not a single technology  HTML and CSS can be used in combination to mark up and style information.AJAX is not a programming language but a combination of A browser built-in XMLHttpRequest object, JavaScript, and HTML DOM (to display or use the data).

Download Source Code: https://findandsolve.com/source-code/code-ajax-example-inasp-dot-net-core


Why use AJAX?

  1. Update a web page or DIV without reloading the page.
  2. Request data from a server and receive data from a server - after the page has loaded.
  3. Send data to a server - in the background.
  4. Making Asynchronous Calls.
  5. In UI-User Friendly.
  6. Improve the speed, performance, and usability of a web application.
  7. In Cascading dropdown and autocomplete like google search.


In the article, we are learning

Ajax (Asynchronous JavaScript and XML) can be used to make asynchronous HTTP requests in ASP.NET Core 5 MVC. Here is an example of how to make an AJAX call to an action method in a controller:

  1. Create a new action method in a controller: In your ASP.NET Core 5 MVC project, create a new action method in a controller that returns a JSON result.

[HttpGet] public IActionResult GetData() { var data = new[] { "item1", "item2", "item3" }; return Json(data); }
  1. Add a view that calls the action method using AJAX: In your Razor view, you can use JavaScript to make an AJAX call to the action method.

<button id="getData">Get Data</button> <ul id="dataList"></ul> <script> $(document).ready(function () { $("#getData").click(function () { $.ajax({ url: "/YourController/GetData", type: "GET", success: function (data) { var items = ""; $.each(data, function (i, item) { items += "<li>" + item + "</li>"; }); $("#dataList").html(items); } }); }); }); </script>
  1. Add the jQuery library to your project: In order to use the $.ajax method, you need to include the jQuery library in your ASP.NET Core 5 MVC project. You can include the library in your HTML file by adding the following code in the <head> section of your HTML document:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

By following these steps, you can make an AJAX call to an action method in your ASP.NET Core 5 MVC project. The action method will return a JSON result, which can be processed by the JavaScript code in the view to dynamically update the page without requiring a full page reload.


Step 1.


  • Create a new Project and choose  the ASP.NET Core web app as the given image

Step 2.


Step 3.


Step 4.

To create StudentViewModel.cs in your Models folder : Right click on Models folder ->Add->class

Step 5.

Open StudentInfoViewModel.cs and page this code in your StudentInfoViewModel.cs

  public class StudentInfoViewModel
    {
        public int StudentId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string StudentCode { get; set; }
        public List<StudentInfoViewModel> StudentList { get; set; }
    } 

Call Partial View Using Ajax in .NET 5

Open HomeController and paste this code

      public ActionResult _PartialExample()
        {
            //create viewmodel object first
            StudentInfoViewModel model = new StudentInfoViewModel();
            // Create a List of objects
            model.StudentList = new List<StudentInfoViewModel>()
            {
                new StudentInfoViewModel {StudentId =101,StudentCode="ST-001", FirstName = "Sanika", LastName = "Bikali"},
                new StudentInfoViewModel {StudentId =102,StudentCode="ST-002", FirstName = "Makila", LastName = "Sothang"},
                new StudentInfoViewModel {StudentId =103,StudentCode="ST-003", FirstName = "Debin", LastName = "Akila"},
                new StudentInfoViewModel {StudentId =104,StudentCode="ST-004", FirstName = "Tulani", LastName = "Adur"}
            };
            return View(model);
        }

  1. Create a partial view page "_PartialExample.cshtml" from HomeController.
  2. Open "_PartialExample.cshtml" and past this code in your _PartialExample.cshtml page as given below.
@model AJAXExampl.Models.StudentInfoViewModel
@{
    Layout = null;
}
    <div class="row">
        <div class="table-responsive-lg">
            <table class="table table-responsive table-hover">
                <thead>
                    <tr>
                        <td>Student Id</td>
                        <td>Student Code</td>
                        <td>First Name</td>
                        <td>Last Name</td>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var item in Model.StudentList)
                    {
                        <tr>
                            <td>@item.StudentId</td>
                            <td>@item.StudentCode</td>
                            <td>@item.FirstName</td>
                            <td>@item.LastName</td>
                        </tr>
                    }
                </tbody>
            </table>
        </div>
    </div>

Now Call this given above partial page from Another View page without page loading

  1. Open your Index.cshtm page from Views->home  and past this in code your "Index.cshtml" as given below
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="container">
    <div class="row">
        <button class="btn btn-primary" id="get_student_list">
            Call Partial
        </button>
    </div>
    <br />
    <br />
    <div id="studentList"></div>
</div>
<script type="text/javascript">
    $(function () {
        $("#get_student_list").click(function () {
            $.ajax({
                type: "GET",
                url: "/Home/_PartialExample",
                success: function (response) {
                    $('#studentList').empty();
                    $('#studentList').html(response);
                },
                failure: function (response) {
                    alert(response.responseText);
                },
                error: function (response) {
                    alert(response.responseText);
                }
            });
        });
    });
</script>

When you clik on your "Call Partial" button you can see this result as give below.


Call json data and bind in DropdownList using ajax

  1. Open your HomeController and past this code as given below.
 public JsonResult BingDataInDropDownList()
        {
            // Create a List of objects
            List<StudentInfoViewModel> studentInfo = new List<StudentInfoViewModel>()
            {
                new StudentInfoViewModel {StudentId =101,FirstName = "Sanika"},
                new StudentInfoViewModel {StudentId =102, FirstName = "Makila"},
                new StudentInfoViewModel {StudentId =103,FirstName = "Debin"},
                new StudentInfoViewModel {StudentId =104, FirstName = "Tulani"}
            };
            return Json(studentInfo);
        }

HTML

Open your cshtml page where you want to call data using ajax and bind in your dropdownlist

 <div class="row">
   <div class="col-sm-6 form-group">
            <button class="btn btn-primary" id="get_dropdown_list">
                Call DropDownList
            </button>
        </div>
     <div class="col-sm-6 form-group">
        <label>Bind Data in DropDownList</label>
        <select class="form-control" id="dropdownlist"></select>
     </div>
</div>

AJAX

$("#get_dropdown_list").click(function () {
            $.get('/Home/BingDataInDropDownList',
                function (data) {
                    $('#dropdownlist').find('option').remove()
                    $(data).each(
                        function (index, item) {
                            $('#dropdownlist').append('<option value="' + item.studentId + '">' + item.firstName + '</option>')
                        });
                }
            );
        });

Output

when you click on your button 



Related information

Sundar  Neupane

Sundar Neupane

I like working on projects with a team that cares about creating beautiful and usable interfaces.

If findandsolve.com felt valuable to you, feel free to share it.

Comments



Report Response