Using AJAX in ASP.NET MVC

Shape Image One

Ajax is the client-side script that communicates from client to server or from server to client side. Ajax speeds up the response. We can implement Ajax in ASP.NET MVC easily. Follow the below steps to implement Ajax in ASP.NET MVC

Step1
First, we will create a table in database where we will mention the props that are required in our page. Simply open SQL server and connect it. Make a database. Create a table in this database then define all the props in table then save this table.

Step2
Create a new project in visual studio. Select the required template then name your project as you want. Select the latest framework. In our case my project name is Demo Application. Then hit create button. Once your project is created the dashboard will looks like this.

Step3
Create EDMX File using ADO.NET which will created inside the Model folder. This edmx file will generate the dB Context class. Simply right click in Model folder then select add, then new Item and then choose ADO.NET and then name it. Complete the required process that are asked in the creating process. This EDMX file will create a table automatically inside this edmx file. The table name and this prop will be same as created in the database. Make a model class here also. See below screen shot how to create edmx file.

In our case my edmx file name is Model and table name is student. My DB Context class is StudentDBContext. Model name is Student. See below screen shot.

Step4
Create a controller in controller folder. Simply right click in controller folder and choose controller then name your controller. In our case my controller name is Student.

Step5
Now create an object of dB Context class that will retrieve the data from the database. Before creating it you must add the namespace of the DbContext class.

Now create Action method. First I have created Index action method that will compile first when the project will run. This is the Get method.

Now create another HttpPost action method, which is createStudent. In this method Am fetching data from database by using ADD method. This will return the Json result. See below codes for HttpPost action method.

Now again create another Json method which will be HttpGet method. In this method am Listing the data in tabular form. This method will also return the Json result. See the below codes for HttpGet method.

Step6
After completing creating the Action method now add views to the HttpPost action method. Name this view as Index, because in our controller the first action method is Index. Add Html codes to display the summit button, and data input field also to display the result in same page. I have used bootstrap class here. Do not forget to pass the model at the top of this view file. See below codes;


@model DemoApplication.Model.StudentVM

@{
    ViewBag.Title = "";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2></h2>
<div class="col-md-12">
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title">Please enter the details below.</h3>
        </div>
        <div class="panel-body">
            <div class="form-group col-md-5">
                <label>Student Name</label>
                <input type="text" name="StudentName" id="StudentName" class="form-control" placeholder="Enter Student Name" required="" />
            </div>
            <div class="form-group col-md-5">
                <label>Student Address</label>
                <input type="text" name="StudentAddress" id="StudentAddress" class="form-control" placeholder="Enter Student Address" required="" />
            </div>          
            <div class="form-group col-md-5">
                <div style="float: right; display:inline-block;">
                    <input class="btn btn-primary" name="submitButton" id="btnSave" value="Save" type="button">
                </div>
            </div>
        </div>
    </div><hr />
    <table id="tblStudent" class="table table-bordered table-striped table-responsive table-hover">
        <thead>
            <tr>
                <th align="left" class="productth">Student ID</th>
                <th align="left" class="productth">Student Name</th>
                <th align="left" class="productth">Student Address</th>               
            </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>
}
           

Step7
Add java script file just after ending the Html codes in the Index view file. Here I have implemented the Ajax.

@section Scripts
{
    <script type="text/javascript">
        $(function () {
            LoadData();
        $("#btnSave").click(function () {
            //alert("");
            var std = {};
            std.studentName = $("#StudentName").val();
            std.studentAddress = $("#StudentAddress").val();
            $.ajax({
                type: "POST",
                url: '@Url.Action("createStudent")',
                data: '{std: ' + JSON.stringify(std) + '}',
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function () {
                   // alert("Data has been added successfully.");
                    LoadData();
                },
                error: function () {
                    alert("Error while inserting data");
                }
            });
            return false;
        });
    });

    function LoadData() {
        $("#tblStudent tbody tr").remove();
        $.ajax({
            type: 'GET',
            url: '@Url.Action("getStudent")',
            dataType: 'json',
            data: { id: '' },
            success: function (data) {
                var items = '';
                $.each(data, function (i, item) {
                    var rows = "<tr>"
                        + "<td class='prtoducttd'>" + item.StudentId + "</td>"
                        + "<td class='prtoducttd'>" + item.StudentName + "</td>"
                        + "<td class='prtoducttd'>" + item.StudentAddress + "</td>"                   
                    + "</tr>";
                    $('#tblStudent tbody').append(rows);
                });
            },
            error: function (ex) {
                var r = jQuery.parseJSON(response.responseText);
                alert("Message: " + r.Message);
                alert("StackTrace: " + r.StackTrace);
                alert("ExceptionType: " + r.ExceptionType);
            }
        });
        return false;
    }
    </script>

Step8
Go to the Route config file and change the action method name and controller name from its default one. In our case my controller is ‘Student’ and action is ‘Index’.

Step9
Go to your Layout page. Add the following scrips after ending the footer section.

@RenderSection("scripts")
    <script src="~/Scripts/jquery-3.7.1.slim.js"></script>
    <script src="~/Scripts/bootstrap.min.js"></script>
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.7.1.min.js"></script>

Step 10
Now run the program by pressing function key +F5. You will see the following result when application runs;

Let we enter Student name as Tapan Tudu. And Student address is Bokaro then hit save button. We will get the result in tabular format like this below;

You can verify that the same data is also inserted in our database.

******************* END ********************

Leave a Reply

Your email address will not be published. Required fields are marked *