jQuery Ajax Call With JSONResult in ASP.NET MVC

This article gives you details about how you can implement jQuery AJAX calls to ASP.NET MVC controller and display JSONResult on view.

For this tutorial, we will use the Northwind database. If you do not have Northwind database you can download from here.

You will have a DropDownList filled with Northwind.Categories table. You may check for ways to bind MVC DropDownList. On selection change of this DropDownList, a jQuery Ajax call will be made to the controller. The controller will return JSONResult and success part of ajax call will display JSONResult.

Follow the below steps to implement jQuery AJAX call to MVC Controller and display JSON result.

  1. Create ASP.NET MVC application

    Open your Visual Studio and create a empty ASP.NET MVC application.

    Click on File -> New Project -> Web -> ASP.NET web application.

    From the next window Select template Empty and from Add folders and core reference choose MVC.

    Name it as AJAXCalls and click Ok. For more details check Getting Started with ASP.NET MVC.

  2. Add Product Model

    We will use a model class to represet the Product entity.

    Right click on Models folder and select Add -> Class name it as Product -> click Ok.

    Add below properties for the Product model.

                
    namespace AJAXCalls.Models
    {
        public class Product
        {
            public string ProductID { get; set; }
    
            public string ProductName { get; set; }
    
            public string QuantityPerUnit { get; set; }
    
            public string UnitPrice { get; set; }
    
            public string UnitsInStock { get; set; }       
    
            public string ReorderLevel { get; set; }
            
        }
    }
                
            

    For detail description see ASP.NET MVC model example.

  3. Add HomeController

    In this step, you will add a simple controller. Right click on the Controllers folder and select Add -> Controller.

    From Add Scaffold window select MVC 5 Controller - Empty and click Add.

    Name it as HomeController.

    Open HomeController from the Controllers folder and add Action method with name ShowCategoryProducts. For more details about Action method ASP.NET MVC Controller Action Method and Action Result.

    Add the below code to ShowCategoryProducts

    
    public ActionResult ShowCategoryProducts()
    {
        List<electListItem> items = new List<SelectListItem>();
    
        items.Add(new SelectListItem
        {
            Text = "Select Category",
            Value = "0",
            Selected = true
        });
    
        items.Add(new SelectListItem { Text = "Beverages", Value = "1" });
    
        items.Add(new SelectListItem { Text = "Condiments", Value = "2" });
    
        items.Add(new SelectListItem { Text = "Confections", Value = "3" });
    
        items.Add(new SelectListItem { Text = "Dairy Products", Value = "4" });
    
        items.Add(new SelectListItem { Text = "Grains/Cereals", Value = "5" });
    
        items.Add(new SelectListItem { Text = "Meat/Poultry", Value = "6" });
    
        items.Add(new SelectListItem { Text = "Produce", Value = "7" });
    
        items.Add(new SelectListItem { Text = "Seafood", Value = "8" });
    
        ViewBag.CategoryType = items;
    
        return View();
    }
                        
                    

    It adds Category details to ViewBag property. These property values will be shown in Category Type DropDownList.

  4. ShowCategoryProducts View

    In this step, you will add an MVC View to display Category and Product details.

    Open HomeController from Controllers folder -> Go to ShowCategoryProducts action method -> right click and select Add View

    It adds a View under Views -> Home folder with the name ShowCategoryProducts.cshmtl.

    Now add a DropDownList to display Categories and empty Table to show products depending on the selected category.

    Add below html to ShowCategoryProducts.cshtml

    
    @{
    ViewBag.Title = "jQuery Ajax Call example in ASP.NET MVC - dotnetmentors.com";
    }
    
    <h1>
        jQuery Ajax Call example in ASP.NET MVC
        - dotnetmentors.com
    </h1>
    @using (Html.BeginForm("CategoryChosen", "Home",
                    FormMethod.Get))
    {
    <table cellspacing="2" cellpadding="2">
        <tr>
            <td>
                Category Type :
            </td>
            <td>
                @Html.DropDownList("CategoryType")
            </td>
        </tr>
    </table>
    
    <br />
        
    <div>
        <table id="tblProducts" class="tblProducts">
            <thead>
                <tr>
                    <th align="left" class="productth">ProductID</th>
                    <th align="left" class="productth">ProductName</th>
                    <th align="left" class="productth">QuantityPerUnit</th>
                    <th align="left" class="productth">UnitPrice</th>
                    <th align="left" class="productth">UnitsInStock</th>
                    <th align="left" class="productth">ReorderLevel</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>
    
    <style type="text/css">
        .tblProducts {
            font-family: verdana,arial,sans-serif;
            font-size: 11px;
            color: #333333;
            border-width: 1px;
            border-color: #666666;
            border-collapse: collapse;
        }
    
        .productth {
            border-width: 1px;
            padding: 8px;
            border-style: solid;
            border-color: #666666;
            background-color: #dedede;
        }
    
        .prtoducttd {
            border-width: 1px;
            padding: 8px;
            border-style: solid;
            border-color: #666666;
            background-color: #ffffff;
        }
    </style>
    }
        
    
  5. Action method to return JSON

    Open HomeController and action method which accepts Category ID as an input parameter, create a list of products whose CategoryID is equal to input parameter and return it as JSON result.

    If you have data in the DataTable or Dataset you can convert datatable to JSON string.

    Add below Action method to HomeController

                
    public JsonResult GetProducts(string id)
    {
    List<Product> products = new List<Product>();
    
    string query = string.Format("SELECT  [ProductID], [ProductName], [QuantityPerUnit],[UnitPrice],[UnitsInStock],[ReorderLevel] " +
        " FROM [Northwind].[dbo].[Products] WHERE CategoryID = {0}",id);
    
    using (SqlConnection con = new SqlConnection("your connection string"))
    {
        using (SqlCommand cmd = new SqlCommand(query, con))
        {
            con.Open(); 
            SqlDataReader reader = cmd.ExecuteReader();
    
            while (reader.Read())
            {
                products.Add(
                    new Product 
                    { 
                        ProductID = reader.GetValue(0).ToString(),
                        ProductName = reader.GetString(1),
                        QuantityPerUnit = reader.GetString(2),
                        UnitPrice = reader.GetValue(3).ToString(),
                        UnitsInStock = reader.GetValue(4).ToString(), 
                        ReorderLevel = reader.GetValue(5).ToString()  
                    }
                );    
            }
        }
    }
    
    return Json(products, JsonRequestBehavior.AllowGet);
    }
            
    

    It creates a list of Products model and returns as JSON.

  6. jQuery AJAX call to MVC controller

    In this step, you will add code for CategoryType DropDownList change event. This will create the AJAX helper to call the MVC controller action method.

    Below is the code which fires on change of DropDownList, create an AJAX call with required details, makes a call to GetProducts controller action method, accepts JSON result, and display as a Table object.

    Add it after </style> of the above code which you added in step 4.

                
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
        
    <script type="text/javascript">
    
    $(document).ready(function () {
    
    $("#CategoryType").change(function () {
    
        $("#tblProducts tbody tr").remove();
    
        $.ajax({
    
            type: 'POST',
    
            url: '@Url.Action("GetProducts")',
            dataType: 'json',
            data: { id: $("#CategoryType").val() },
            success: function (data) {
                var items = '';
                $.each(data, function (i, item) {
    
                    var rows = "<tr>"
                    + "<td class='prtoducttd'>" + item.ProductID + "</td>"
                    + "<td class='prtoducttd'>" + item.ProductName + "</td>"
                    + "<td class='prtoducttd'>" + item.QuantityPerUnit + "</td>"
                    + "<td class='prtoducttd'>" + item.UnitPrice + "</td>"
                    + "<td class='prtoducttd'>" + item.UnitsInStock + "</td>"
                    + "<td class='prtoducttd'>" + item.ReorderLevel + "</td>"
                    + "</tr>";
                    $('#tblProducts 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>
    
            
    

    On success it displays the JSON string returned by action method, manipulate it and display product details on View.

    Execute your application and browse to http://localhost:<portnumber>/home/ShowCategoryProducts.

    Select any value from CategoryType DropDownList. It makes an AJAX call to fill Products table. It display below screen.

    jQuery Ajax Call in ASP.NET MVC example

Source code on Git hub Source Code on Github

Speak your mind
Please login to post your comment!


  • geeksarray user
    08/27/2015 11:55 PM Chinju

    Superb !

  • geeksarray user
    01/22/2016 10:38 PM rash

    i want an example of how to use jquery ajax with code first approach in mvc for crud opration using single view

  • geeksarray user
    01/01/2018 04:35 AM boopathiysd

    thank you for your information sharing!

Blog Search





If you like my content please feel free to buy me coffee. Buy Me A Coffee