Sometimes you may need to load data dynamically based on user input or data based on user selected dropdown list, then you can implement jQuery Ajax call to controller and get JSON data in return and append it to your View, so let's understand it, how we can achieve it using ASP.NET MVC & jQuery Ajax.
What are we going to Learn?
-> In this article, you will learn how to load get JSON data from MVC controller using jQuery AJAX and then injecting that JSON data into HTML
Step 1: Create a new project in Visual Studio by navigating to File -> New Project -> Web -> ASP.NET web application.
Give a name(jQueryAjaxWithJSON) to your application and Click 'OK', then Select 'MVC' template to generate default data with your project.
Step 2: Let's add a Model in 'Models' folder, right click on create, Select 'Add' then select 'Class' and the below class (Products.cs)
public class Products
{
public string ProductName { get; set; }
public string Price { get; set; }
}
Step 3: Connect to database using ADO.NET, before we proceed, here is the image of the database which I will be using in this example:
To connect to the database, you need to, Right click on 'Models' folder, Select 'Add', click 'New item' and then from left pane select'Data', while in the right select 'ADO.NET Enitty Data model'
Name it as shown in the above image, Click 'Add'
Click 'Next', and then Click on "New Connection".
In the New tab enter all your details like Server Name, your local DB, username/password and the database to which you have to connect(here ProductsDB) , 'Test Connection' if needed
Click "Ok", then select "Yes, include sensitive data in the connection string", Click"Next", now select specific table or all tables rfom the screen
Click 'Finish' and you will find the your EDMX created as below
Step 4: Go to your HomeController, In the Index ActionMethod we will create dropdown list using ViewBag to show all Categories Dropdown list, so here the code for it
private ProductsDBEntities dBEntities = new ProductsDBEntities();
public ActionResult Index()
{
ViewBag.DDL = dBEntities.ProductCategories.ToList();
return View();
}
In your View, to show the dropdown list created above you need to paste Razor syntax as belo
@Html.DropDownList("ProductCategoryDDL", new SelectList(ViewBag.DDL, "Id", "ProductCategoryName",1), new { @class="form-control"})
Now as we need to show Products in the table we will create a HTML tabe, but with empty body, which we will fill with JSON data
<br/>
@Html.DropDownList("ProductCategoryDDL", new SelectList(ViewBag.DDL, "Id", "ProductCategoryName",1), new { @class="form-control"})
<br/>
<table class="table table-bordered table-condensed">
<thead>
<tr>
<th>Product Name</th>
<th>Price ($)</th>
</tr>
</thead>
<tbody id="tblBody">
</tbody>
</table>
Right now we have DDL and empty HTML, now to place the data dynamically on changing dropdown list value we will need jQuery AJAX call to controller which will return us JSON data and by looping JSON data and converting it into HTML, we will append it to HTML body
<script>
$(document).ready(function () {
//Load item using JSON on page load
$.get('/Home/GetProducts/' + $("#ProductCategoryDDL").val(), function (data) {
//create a empty string to append data
var str = "";
//loop through data
$.each(data, function (index, item) {
//get each list item returned value and add it as string
str = str + "<tr><td>" + item.ProductName + "</td><td>" + item.Price + "</td></tr>";
});
//append item in Table body to
$("#tblBody").html(str);
});
//function to execute on Select list value change
$("#ProductCategoryDDL").on('change', function () {
var SelectedId = $(this).val();
$.get('/Home/GetProducts/' + SelectedId, function (data) {
//create a empty string to append data
var str = "";
//loop through data
$.each(data, function (index, item) {
//get each list item returned value and add it as string
str = str + "<tr><td>" + item.ProductName + "</td><td>" + item.Price + "</td></tr>";
});
//append item in Table body to
$("#tblBody").html(str);
});
});
});
</script>
In the above script, after complete page load we are calling ActionMethod 'Home/GetProducts' and passing first selected DDL value, which will return Data of selected items, then looping each value, and creating a string of html table row(<tr>) and table data(<td>) with table data as ProductName and Price.
Same code, is applied to fetch data on Dropdownlist value change.
So your Complete Index View code will be
@{
ViewBag.Title = "Home Page";
}
<br/>
@Html.DropDownList("ProductCategoryDDL", new SelectList(ViewBag.DDL, "Id", "ProductCategoryName",1), new { @class="form-control"})
<br/>
<table class="table table-bordered table-condensed">
<thead>
<tr>
<th>Product Name</th>
<th>Price ($)</th>
</tr>
</thead>
<tbody id="tblBody">
</tbody>
</table>
@section scripts{
<script>
$(document).ready(function () {
//Load item using JSON on page load
$.get('/Home/GetProducts/' + $("#ProductCategoryDDL").val(), function (data) {
//create a empty string to append data
var str = "";
//loop through data
$.each(data, function (index, item) {
//get each list item returned value and add it as string
str = str + "<tr><td>" + item.ProductName + "</td><td>" + item.Price + "</td></tr>";
});
//append item in Table body to
$("#tblBody").html(str);
});
//function to execute on Select list value change
$("#ProductCategoryDDL").on('change', function () {
var SelectedId = $(this).val();
$.get('/Home/GetProducts/' + SelectedId, function (data) {
//create a empty string to append data
var str = "";
//loop through data
$.each(data, function (index, item) {
//get each list item returned value and add it as string
str = str + "<tr><td>" + item.ProductName + "</td><td>" + item.Price + "</td></tr>";
});
//append item in Table body to
$("#tblBody").html(str);
});
});
});
</script>
}
In your HomeController, let's create the ActionMethod which return JSON data to the AJAX
public JsonResult GetProducts(int id)
{
var Products = dBEntities.ProductsMainTables.Where(a => a.ProductCategoryId == id)
//Select items in new class to avoid circular reference error
.Select(a=> new Products { Price=a.Price , ProductName=a.ProductName })
.ToList();
//do not forget to add JsonRequestBehavior.AllowGet as our request is GET request,
//otherwise you may get error
return Json(Products,JsonRequestBehavior.AllowGet);
}
Note: To stay away from JSON error like Circular reference we have created elements of New Products class and selected ProductName & Price only
Step 5: Build your project, you will see screen like below
on changing dropdown list you may see that table body data changes, here is the image with console view of the browser
Complete working output, sample
Please feel free to ask questions related to it, if you have any doubts, thanks