jQuery Ajax Call With JSONResult in ASP.NET MVC

Hi experts,

I'm doing this mvc json example.
http://dotnetmentors.com/mvc/jquery-ajax-call-with-jsonresult-in-asp-net-mvc.aspx

Example 1 below works just fine and works just like the example in the link above.
Example 2 is the one i need help with.

I recreated this example using sql server 2008, Visual Studio 2013, mvc 5, C#, Razor.
My example uses the Products table from the Northwind database.

Example 1

My directory looks like this:
my directory
This is my code:

HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
//
using System.Data;
using System.Data.SqlClient;
using SampleApp.Models;
using System.Configuration;

namespace SampleApp.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {

            List<SelectListItem> 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();
        }


        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);

            // create SqlConnection object
            string ConnectionString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;

            using (SqlConnection con = new SqlConnection(ConnectionString))
            {
                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);
        }



    }
}

Open in new window




Index.cshtml

@{
    ViewBag.Title = "Index";
}
<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>

<h1>jQuery Ajax Call example in ASP.NET MVC</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>
}

Open in new window


My connection string in my web.config looks like this:

<add name="NorthwindConnectionString" connectionString="Data Source=MyServer\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.SqlClient" />


So when I run Example 1. It works just fine.

On launch I see this:

on page load
After i select an item from the dropdownlist then the table is filled with data an looks like this:

after selecting an item from the ddl

If you notice, in the controller, there is a JSON method called GetProducts which is used for the data of the table.

the JSON method of Example 1

        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);

            // create SqlConnection object
            string ConnectionString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;

            using (SqlConnection con = new SqlConnection(ConnectionString))
            {
                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);
        }

Open in new window



Example 2

For example 2 I'm recreating example 1.
In example 2 though I'm going to be using the Entity Framework database first model approach and linq in the GetProducts method to bind my data to the table.

This is the directory for example 2

example 2 directory
Northwind.edmx model looks like this:

NorthwindEntity model
HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
//
using System.Data;
using System.Data.SqlClient;
using SampleApp.Models;
using System.Configuration;

namespace SampleApp.Controllers
{
    public class HomeController : Controller
    {

        private NorthwindEntities db = new NorthwindEntities();

        // GET: Home
        public ActionResult Index()
        {

            List<SelectListItem> 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();
        }


        [HttpPost]
        public JsonResult GetProducts(string id)
        {
            JsonResult result = null;

            List<SampleApp.Models.Product> rProduct = null;

            rProduct = db.Products.ToList();

            result = Json(rProduct.Select(r => new
            {
                categoryid = r.CategoryID.ToString(),
                productid = r.ProductID.ToString(),
                productname = r.ProductName,
                quantityperunit = r.QuantityPerUnit,
                unitprice = r.UnitPrice.ToString(),
                unitsinstock = r.UnitsInStock.ToString(),
                reorderlevel = r.ReorderLevel.ToString()
            }).Where(r => r.categoryid.Contains(id)), JsonRequestBehavior.AllowGet);
            
            return result;
        }


    }
}

Open in new window


Index.cshtml


@{
    ViewBag.Title = "Index";
}
<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>

<h1>jQuery Ajax Call example in ASP.NET MVC</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>
}

Open in new window


my connection string in Web.config

<add name="NorthwindEntities" connectionString="metadata=res://*/Models.Northwind.csdl|res://*/Models.Northwind.ssdl|res://*/Models.Northwind.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=MyServer\SQLEXPRESS;initial catalog=Northwind;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /></connectionStrings>

Open in new window


When I run my page and select and item from my ddl I get this:

when i run example 2

I believe my error is in my GetProducts method.

Anyone know where my code is wrong in Example 2?
LVL 1
maqskywalkerAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

zephyr_hex (Megan)DeveloperCommented:
To further troubleshoot your issue, I'd recommend you drop a breakpoint on line 64 of your HomeController and walk through what's happening with the query.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.