JSON Data With ASP.NET MVC Using jQuery

Today, I am going to explain how to get the JSON data with ASP.NET MVC to make AJAX call using jQuery. As we know, JSON is very light-weight as compared to XML or other datasets, so, in this article, I will create a blog system for a demo where first, you will bind the DropDownList with blog categories and on selection of individual category, respective blog details will be populated. For this demonstration, I have used Code First approach.

DOWNLOAD CODE

To create new ASP.NET MVC application.

Open Visual Studio 2015/2013.

Go to File menu and select New >> New Project.

It will display the following new project window where you can choose different types of project. So, from the right panel, you need to choose Templates >> Visual C# >> Web.

After that, from the left panel, you need to choose ASP.NET Web application. Give suitable name to the project as “JSONWithAspNetMVCExample” and click OK.

JSONWithAspNetMVCExample

It will open another window where we can choose different templates for ASP.NET applications. So, here we need to go with MVC template and click OK.

JSONWithAspNetMVCExample

Create Entity and DataContext Class

As in this article, we are using two entities to make blog system, so I am using two entities - category and blog. Basically, the entire categories will display inside the DropDownList and based on the DropDownList value selection, blog details will be binded with html table using jQuery. So, there are two entity classes required.

Blog.cs

Following is the blog class where properties are defined. I have used Table attribute with class name because for this, it will take same name and a table will be created inside the database when you run the application first. Since we are using Code First approach, model or entity is created first and on the basis of that, database and tables are generated.

  1. using System;  
  2. using System.ComponentModel.DataAnnotations.Schema;  
  3. using System.ComponentModel.DataAnnotations;  
  4. namespace JsonWithAspNetMVCExample.Models {  
  5.     [Table("NextPosts")]  
  6.     public class Blog {  
  7.         [Key]  
  8.         public int PostId {  
  9.             get;  
  10.             set;  
  11.         }  
  12.         [MaxLength(500)]  
  13.         [Column(TypeName = "varchar")]  
  14.         public string PostTitle {  
  15.             get;  
  16.             set;  
  17.         }  
  18.         [MaxLength(1000)]  
  19.         [Column(TypeName = "text")]  
  20.         public string ShortPostContent {  
  21.             get;  
  22.             set;  
  23.         }  
  24.         [Column(TypeName = "text")]  
  25.         public string FullPostContent {  
  26.             get;  
  27.             set;  
  28.         }  
  29.         [MaxLength(255)]  
  30.         public string MetaKeywords {  
  31.             get;  
  32.             set;  
  33.         }  
  34.         [MaxLength(500)]  
  35.         public string MetaDescription {  
  36.             get;  
  37.             set;  
  38.         }  
  39.         public DateTime PostAddedDate {  
  40.             get;  
  41.             set;  
  42.         }  
  43.         public int CategoryId {  
  44.             get;  
  45.             set;  
  46.         }  
  47.         //public virtual int CategoryId { get; set; }  
  48.         //[ForeignKey("CategoryId")]  
  49.         //public virtual Category Categories { get; set; }  
  50.     }  
  51. }  
Category.cs

Following is the category model, where all the properties have defined for blog's category.
  1. using System.ComponentModel.DataAnnotations;  
  2. using System.ComponentModel.DataAnnotations.Schema;  
  3. namespace JsonWithAspNetMVCExample.Models {  
  4.     [Table("NextCategories")]  
  5.     public class Category {  
  6.         [Key]  
  7.         [Required(ErrorMessage = "Category is required")]  
  8.         public int CategoryId {  
  9.             get;  
  10.             set;  
  11.         }  
  12.         [MaxLength(25)]  
  13.         public string CategoryName {  
  14.             get;  
  15.             set;  
  16.         }  
  17.     }  
  18. }  
So, it is time to create data access classes for Code First approach. I have given it the name "BlogContext" . Inside this class, I have created DbSet for those classes which are participating in blog application. I have also given here the name of database connection [testconnection].
  1. using System.Data.Entity;  
  2. namespace JsonWithAspNetMVCExample.Models {  
  3.     public class BlogContext: DbContext {  
  4.         public BlogContext(): base("testConnection") {}  
  5.         public DbSet < Blog > Blogs {  
  6.             get;  
  7.             set;  
  8.         }  
  9.         public DbSet < Category > Categories {  
  10.             get;  
  11.             set;  
  12.         }  
  13.     }  
  14. }  
Create Database Connection

Now, first I am going to create connection string for database access, which is basically inside the web.config. I have used these names only for testing purposes; you can change it as per your convenience. Be sure before running the application that you have made changes in username and password as per your SQL Server.
  1. <connectionStrings>  
  2.     <add name="testConnection" connectionString="Data Source=DEL9043B\SQLEXPRESS2012;database = demo; uid=sa; password=yourpassword" providerName="System.Data.SqlClient" />   
  3. </connectionStrings>  
Create Blog Controller

When user requests for the particular page in ASP.NET MVC, it first goes to Controller and as per routing configuration, Controller decides which action needs to be executed. So this time, I am going to create a new Controller as "BlogController".

To create the Controller, right click on Controllers folder from solution and choose Add >> Controller. It will open a popup window where you can provide the name for the Controller and click on Add.

 Create Blog Controller

Make changes in BlogController class as following, to get the categories data as well as blogs data based on the category value selection from the database. As you can see with following code, I have used JsonResult GetBlogDetailByCategoryID(int categoryId) which is returning JSON Result.
  1. using JsonWithAspNetMVCExample.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web.Mvc;  
  6. namespace JsonWithAspNetMVCExample.Controllers {  
  7.     public class BlogController: Controller {  
  8.         BlogContext db = null;  
  9.         // GET: Blog  
  10.         public BlogController() {  
  11.             db = new BlogContext();  
  12.         }  
  13.         public ActionResult Index() {  
  14.             List < SelectListItem > blogCategories = new List < SelectListItem > ();  
  15.             blogCategories.Add(new SelectListItem {  
  16.                 Text = "Select Category", Value = "0", Selected = true  
  17.             });  
  18.             var categories = db.Categories.ToList();  
  19.             foreach(var c in categories) {  
  20.                 blogCategories.Add(new SelectListItem {  
  21.                     Text = c.CategoryName, Value = Convert.ToString(c.CategoryId)  
  22.                 });  
  23.             }  
  24.             ViewBag.CategoryList = blogCategories;  
  25.             return View();  
  26.         }  
  27.         public JsonResult GetBlogDetailByCategoryID(int categoryId) {  
  28.             List < Blog > blogs = new List < Blog > ();  
  29.             blogs = db.Blogs.Where(x => x.CategoryId == categoryId).Take(5).ToList();  
  30.             return Json(blogs, JsonRequestBehavior.AllowGet);  
  31.         }  
  32.     }  
  33. }  
I am using Index page where all the categories will bind at the time of loading. So, I have used @Html.DropDownList("CategoryList") which will bind the ViewBag categories data on page load and show all the categories inside DropDownList.

To display blog details which belong to selected category in DropDownList, I am making an AJAX call which will directly hit to GetBlogDetailByCategoryID action method on BlogController and get appropriate data to bind it with html table.
  1. <script type="text/javascript">  
  2.     $(document).ready(function() {  
  3.         $("#CategoryList").change(function() {  
  4.             $.ajax({  
  5.                 type: 'GET',  
  6.                 url: '@Url.Action("GetBlogDetailByCategoryID")',  
  7.                 datatype: JSON,  
  8.                 data: {  
  9.                     'categoryId': $("#CategoryList").val()  
  10.                 },  
  11.                 success: function(data) {  
  12.                     $('#blogTable tbody').empty();  
  13.                     $.each(data, function(i, item) {  
  14.                         var rows = "<tr>" + "<td>" + item.PostId + "</td>" + "<td>" + item.PostTitle + "</td>" + "<td>" + item.ShortPostContent + "</td>" + "<td>" + item.MetaDescription + "</td>" + "</tr>";  
  15.                         $('#blogTable tbody').append(rows);  
  16.                     });  
  17.                 },  
  18.                 error: function(data) {}  
  19.             });  
  20.         });  
  21.     });  
  22. </script>  
Index.html
  1. @{  
  2. ViewBag.Title = "Index";  
  3. Layout = "~/Views/Shared/_Layout.cshtml";  
  4. }  
  5.   
  6. <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>  
  7. <script type="text/javascript">  
  8. $(document).ready(function () {  
  9. $("#CategoryList").change(function () {  
  10. $.ajax({  
  11. type: 'GET',  
  12. url: '@Url.Action("GetBlogDetailByCategoryID")',  
  13. datatype: JSON,  
  14. data: { 'categoryId': $("#CategoryList").val() },  
  15. success: function (data) {  
  16. $('#blogTable tbody').empty();  
  17.   
  18. $.each(data, function (i, item) {  
  19. var rows = "  
  20.     <tr>"  
  21. + "  
  22.         <td>" + item.PostId + "</td>"  
  23. + "  
  24.         <td>" + item.PostTitle + "</td>"  
  25. + "  
  26.         <td>" + item.ShortPostContent + "</td>"  
  27. + "  
  28.         <td>" + item.MetaDescription + "</td>"  
  29. + "  
  30.     </tr>";  
  31. $('#blogTable tbody').append(rows);  
  32. });  
  33. },  
  34. error: function (data) { }  
  35. });  
  36. });  
  37. });  
  38.   
  39. </script>  
  40. <style type="text/css">  
  41. .zui-table {  
  42. border: solid 1px #DDEEEE;  
  43. border-collapse: collapse;  
  44. border-spacing: 0;  
  45. width:100%;  
  46. font: normal 13px Arial, sans-serif;  
  47. }  
  48.   
  49. .zui-table thead th {  
  50. background-color: #DDEFEF;  
  51. border: solid 1px #DDEEEE;  
  52. color: #336B6B;  
  53. padding: 10px;  
  54. text-align: left;  
  55. }  
  56.   
  57. .zui-table tbody td {  
  58. border: solid 1px #DDEEEE;  
  59. color: #333;  
  60. padding: 10px;  
  61. }  
  62.   
  63. .zui-table-rounded {  
  64. border: none;  
  65. }  
  66.   
  67. .zui-table-rounded thead th {  
  68. background-color: #CFAD70;  
  69. border: none;   
  70. color: #333;  
  71. }  
  72.   
  73. .zui-table-rounded thead th:first-child {  
  74. border-radius: 10px 0 0 0;  
  75. }  
  76.   
  77. .zui-table-rounded thead th:last-child {  
  78. border-radius: 0 10px 0 0;  
  79. }  
  80.   
  81. .zui-table-rounded tbody td {  
  82. border: none;  
  83. border-top: solid 1px #957030;  
  84. background-color: #EED592;  
  85. }  
  86.   
  87. .zui-table-rounded tbody tr:last-child td:first-child {  
  88. border-radius: 0 0 0 10px;  
  89. }  
  90.   
  91. .zui-table-rounded tbody tr:last-child td:last-child {  
  92. border-radius: 0 0 10px 0;  
  93. }  
  94. </style>  
  95. <table>  
  96.     <tr>  
  97.         <td>  
  98.             <h2> Get JSON Data with Asp.Net MVC</h2>  
  99.             <br />  
  100.         </td>  
  101.     </tr>  
  102.     <tr>  
  103.         <td>  
  104. Select Category : @Html.DropDownList("CategoryList")  
  105. </td>  
  106.     </tr>  
  107. </table>  
  108. <br />  
  109. <table id="blogTable" class="zui-table zui-table-rounded">  
  110.     <thead>  
  111.         <tr>  
  112.             <th>PostId</th>  
  113.             <th>Title</th>  
  114.             <th>Full Content</th>  
  115.             <th>Meta Description</th>  
  116.         </tr>  
  117.     </thead>  
  118.     <tbody></tbody>  
  119. </table>  
When you run this application the first time and since we are using Code First Approach, the database and tables will be created automatically. So, when you check the database, there will be a test database created with two tables as NextCategories and NextPosts, as shown in the following image because these names are defined in Model class using table attributes.

attributes

These tables are empty. So, you can run the following scripts to insert the dummy data in both the tables.
  1. Use Test  
  2. Go  
  3.   
  4. -- Insert Records for categories  
  5.   
  6. INSERT INTO NextCategories VALUES ('CSharp')  
  7. INSERT INTO NextCategories VALUES ('MVC')  
  8. INSERT INTO NextCategories VALUES ('Asp.Net')  
  9. INSERT INTO NextCategories VALUES ('HTML')  
  10. INSERT INTO NextCategories VALUES ('AngularJS')  
  11.   
  12. -- Insert Records for blogs  
  13.   
  14. INSERT INTO NextPosts VALUES ('CSharp Title 1''CSharp Short Description 1','CSharp Long Description 1''CSharp Keyword 1''CSharp Description 1', GETDATE(), 1 )  
  15. INSERT INTO NextPosts VALUES ('MVC Title 1''MVC Short Description 1','MVC Long Description 1''MVC Keyword 1''MVC Description 1', GETDATE(), 2 )  
  16. INSERT INTO NextPosts VALUES ('MVC Title 2''MVC Short Description 2','MVC Long Description 2''MVC Keyword 2''MVC Description 2', GETDATE(), 2 )  
  17. INSERT INTO NextPosts VALUES ('AngularJS Title 1''AngularJS Short Description 1','AngularJS Long Description 1''AngularJS Keyword 1''AngularJS Description 1', GETDATE(), 5 )  
  18. INSERT INTO NextPosts VALUES ('HTML Title 1''HTML Short Description 1','HTML Long Description 1''HTML Keyword 1''HTML Description 1', GETDATE(), 4 )  
  19. INSERT INTO NextPosts VALUES ('CSharp Title 2''CSharp Short Description 2','CSharp Long Description 2''CSharp Keyword 2''CSharp Description 2', GETDATE(), 1 )  
  20. INSERT INTO NextPosts VALUES ('HTML Title 2''HTML Short Description 2','HTML Long Description 2''HTML Keyword 2''HTML Description 2', GETDATE(), 4 )  
  21. INSERT INTO NextPosts VALUES ('Asp.Net Title 1''Asp.Net Short Description 1','Asp.Net Long Description 1''Asp.Net Keyword 1''Asp.Net Description 1', GETDATE(), 3)  
  22. INSERT INTO NextPosts VALUES ('HTML Title 3''HTML Short Description 3','HTML Long Description 3''HTML Keyword 3''HTML Description 3', GETDATE(), 4 )  
  23. INSERT INTO NextPosts VALUES ('AngularJS Title 2''AngularJS Short Description 2','AngularJS Long Description 2''AngularJS Keyword 2''AngularJS Description 2', GETDATE(), 5 )  
  24. INSERT INTO NextPosts VALUES ('AngularJS Title 3''AngularJS Short Description 3','AngularJS Long Description 3''AngularJS Keyword 3''AngularJS Description 3', GETDATE(), 5 )  
Now, it's time to run the application to see the output. So, pressF5 and select any category. You will see that corresponding blogs will show under this when you select CSharp as category from DropDownList.

DropDownList
If you select any other blog category, it will show corresponding blog details, as per the following image.

DropDownList

Conclusion

So, today, we learned how to create an ASP.NET MVC application and bind the DropDownList and get JSON result from database tobind it to the html table, using jQuery and Code First approach.

I hope this post will help you. If you have any doubts, please ask your doubts or queries in the comment section. If you like this post, please share it with your friends.