CodeDigest.Com Logo
Featured:

Using jQuery Ajax Methods to Get JSON Result from Controller in Asp.Net MVC

Tagged as: Asp.Net MVC jQuery Posted By

One of my previous article Making Ajax Calls to Controller Action Using Asp.Net MVC Ajax Helper Methods discussed about making Ajax calls to a controller action method using the inbuilt Ajax HTML helper methods. In this article, let’s understand how to use the Ajax method available in jQuery library to call controller action method in Asp.Net MVC applications.

Similar to my previous article, let’s build an Employee-Details view by using a simple Employee-Department model. We will display a list of employees in a table and we will make an Ajax call using jQuery to fetch the details as JSON string and populate it in a Details div similar to below.

On click of Delete link let’s make another Ajax call to delete the employee row using jQuery Ajax.

To demonstrate this, let’s create an Asp.Net MVC 5.0 website using Visual Studio 2015 and create the Employee-Department model. We will use Entity Framework Code First for doing data access. Include the latest jQuery library into the project. You can use Nuget package manager to do that. Full source code is attached at the end of this article for reference.

 

 

Let’s first build Employee list page with the Details and Delete link first. The below action and EmployeeSummary view will help us do that.

EmployeeList Action Method

public ActionResult EmployeeSummary()
{
    IList<Employee> empSummary = db.Employees.ToList();
    return View(empSummary);
}
 

EmployeeSummary.cshtml

@using EmployeeMaintenance.Models;
@model IEnumerable<Employee>
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@section css {
}

<h2>Employee List</h2>
<div>
    @Html.ActionLink("Index", "Index", "Home")
</div>

<div>
    <table class="table table-bordered table-condensed">
        <tr>
            <th>Name</th>
            <th>Department</th>
            <th>jQuery AJAX</th>
        </tr>
        @foreach (Employee emp in Model)
        {
            <tr id="tr@(emp.EmployeeId)">
                <td>
                    @Html.ActionLink(String.Format("{0} {1}", emp.FirstName, emp.LastName), "Details", new { id = emp.EmployeeId })
                </td>
                <td>
                    @emp.Department.DepartmentName
                </td>
                <td>
                    <a class="details" id="@emp.EmployeeId" href="#">Details</a> |
                    <a class="delete" id="@emp.EmployeeId" href="#">Delete</a>
                </td>
            </tr>
        }
    </table>
</div>
<div id="details">

</div>
@section scripts {
}
 

In the above view, we have defined a div with id details to fill the employee detail by making Ajax call using jQuery. The id attribute in the Details and Delete hyperlink will help the jQuery to get the current row’s employee id to fetch the details from the server. I have included 2 section in Layout page, one for css and another for scripts for using in content view page. With this, we will built the action method that returns the employee detail as JSON string.

The below detailasjson() action method will return the employee details as JSON string.

Details Action Method

public JsonResult detailasjson(int id)
{
    return Json(db.Employees.Where(e => e.EmployeeId == id).FirstOrDefault(), JsonRequestBehavior.AllowGet);
}
 

Now, let’s code our jQuery events to make a Ajax call to detailsasjson() action method to get the json result and populate the details div using $.Ajax() method in jQuery. For simplicity, I have built the details HTML content manually you can use some free templates. Code below.

@section scripts {
    <script type="text/javascript">
        $(document).ready(function () {
            $('a.details').click(function () {
                var id = $(this).attr("id");
                $.ajax({
                    url: '/employee/detailasjson', type: "GET", dataType: "json",
                    data: {id:id},
                    success: function (data) {
                        content = "<h3>Employee Detail</h3>";
                        content += "<dl class=\"dl-horizontal\">";
                        content += "<dt>First Name</dt><dd>" + data.FirstName + "</dd>";
                        content += "<dt>Last Name</dt><dd>" + data.LastName + "</dd>";
                        content += "<dt>Address1</dt><dd>" + data.Address1 + "</dd>";
                        content += "<dt>Address2</dt><dd>" + data.Address2 + "</dd>";
                        content += "<dt>City</dt><dd>" + data.City + "</dd>";
                        content += "<dt>State</dt><dd>" + data.State + "</dd>";
                        content += "<dt>Country </dt><dd>" + data.Country + "</dd>";
                        content += "<dt>PostalCode</dt><dd>" + data.PostalCode + "</dd>";
                        content += "<dt>Email </dt><dd>" + data.Email + "</dd>";
                        content += "<dt>DOB </dt><dd>" + data.DOB + "</dd>";
                        content += "<dt>Gender </dt><dd>" + data.Gender + "</dd>";
                        content += "<dt>IsPermanent </dt><dd>" + data.IsPermanent + "</dd>";
                        content += "<dt>Salary </dt><dd>" + data.Salary + "</dd>";
                        content += " </dl>";
                        $('#details').html(content);
                    },
                    error: function (xhr, status, error) {
                        alert(xhr.responseText);
                        alert(status);
                        alert(error);                        
                    }
                });

            });
        });

    </script>
}
 

You can now execute and see it employee details getting populated in the details div. I have include error call-back method just in case if we need to debug Ajax errors.

Next, let’s build delete action and call the action method from jQuery. The below code will help you do that.

Delete Action

[HttpPost]
public ActionResult delete(int id)
{
    Employee emp = db.Employees.Where(e => e.EmployeeId == id).FirstOrDefault();
    if(emp != null)
    {
        db.Employees.Remove(emp);
        db.SaveChanges();
        return Content("Deleted Successfully!");
    }
    return Content("Error!");
}
 

jQuery Delete event

$('a.delete').click(function () {
    var id = $(this).attr("id");
    $.ajax({
        url: '/employee/delete', type: "POST", dataType: "text",
        data: { id: id },
        success: function (data) {                       
            $('#tr' + id).html(data);
        },
        error: function (xhr, status, error) {
            alert(xhr.responseText);
            alert(status);
            alert(error);
        }
    });
});
 

You can include the above delete event into the scripts section in EmployeeSumary view.

Thus, we have learnt how to make Ajax calls using jQuery Ajax methods and using Ajax helper methods in Asp.Net MVC application in this article series. You can download the source and see it in action!

 



Feedback

Comments

the pi
the p[i
Commented by pi tyasl on 3/30/2022 3:03:01 AM

Code Color & Code bg Color
Hello. I'm Ali from Iran. I was reviewing your code, but you have chosen bad colors for your codes. Please select black bg color and green and yellow or white for codes.
Commented by Ali on 12/5/2020 2:28:21 AM

thank you
perfect article. thank you
Commented by Subaie on 7/20/2017 9:13:07 PM