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.

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.
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.
- using System;
- using System.ComponentModel.DataAnnotations.Schema;
- using System.ComponentModel.DataAnnotations;
- namespace JsonWithAspNetMVCExample.Models {
- [Table("NextPosts")]
- public class Blog {
- [Key]
- public int PostId {
- get;
- set;
- }
- [MaxLength(500)]
- [Column(TypeName = "varchar")]
- public string PostTitle {
- get;
- set;
- }
- [MaxLength(1000)]
- [Column(TypeName = "text")]
- public string ShortPostContent {
- get;
- set;
- }
- [Column(TypeName = "text")]
- public string FullPostContent {
- get;
- set;
- }
- [MaxLength(255)]
- public string MetaKeywords {
- get;
- set;
- }
- [MaxLength(500)]
- public string MetaDescription {
- get;
- set;
- }
- public DateTime PostAddedDate {
- get;
- set;
- }
- public int CategoryId {
- get;
- set;
- }
- //public virtual int CategoryId { get; set; }
- //[ForeignKey("CategoryId")]
- //public virtual Category Categories { get; set; }
- }
- }
Following is the category model, where all the properties have defined for blog's category.
- using System.ComponentModel.DataAnnotations;
- using System.ComponentModel.DataAnnotations.Schema;
- namespace JsonWithAspNetMVCExample.Models {
- [Table("NextCategories")]
- public class Category {
- [Key]
- [Required(ErrorMessage = "Category is required")]
- public int CategoryId {
- get;
- set;
- }
- [MaxLength(25)]
- public string CategoryName {
- get;
- set;
- }
- }
- }
- using System.Data.Entity;
- namespace JsonWithAspNetMVCExample.Models {
- public class BlogContext: DbContext {
- public BlogContext(): base("testConnection") {}
- public DbSet < Blog > Blogs {
- get;
- set;
- }
- public DbSet < Category > Categories {
- get;
- set;
- }
- }
- }
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.
- <connectionStrings>
- <add name="testConnection" connectionString="Data Source=DEL9043B\SQLEXPRESS2012;database = demo; uid=sa; password=yourpassword" providerName="System.Data.SqlClient" />
- </connectionStrings>
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.

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.
- using JsonWithAspNetMVCExample.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web.Mvc;
- namespace JsonWithAspNetMVCExample.Controllers {
- public class BlogController: Controller {
- BlogContext db = null;
- // GET: Blog
- public BlogController() {
- db = new BlogContext();
- }
- public ActionResult Index() {
- List < SelectListItem > blogCategories = new List < SelectListItem > ();
- blogCategories.Add(new SelectListItem {
- Text = "Select Category", Value = "0", Selected = true
- });
- var categories = db.Categories.ToList();
- foreach(var c in categories) {
- blogCategories.Add(new SelectListItem {
- Text = c.CategoryName, Value = Convert.ToString(c.CategoryId)
- });
- }
- ViewBag.CategoryList = blogCategories;
- return View();
- }
- public JsonResult GetBlogDetailByCategoryID(int categoryId) {
- List < Blog > blogs = new List < Blog > ();
- blogs = db.Blogs.Where(x => x.CategoryId == categoryId).Take(5).ToList();
- return Json(blogs, JsonRequestBehavior.AllowGet);
- }
- }
- }
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.
- <script type="text/javascript">
- $(document).ready(function() {
- $("#CategoryList").change(function() {
- $.ajax({
- type: 'GET',
- url: '@Url.Action("GetBlogDetailByCategoryID")',
- datatype: JSON,
- data: {
- 'categoryId': $("#CategoryList").val()
- },
- success: function(data) {
- $('#blogTable tbody').empty();
- $.each(data, function(i, item) {
- var rows = "<tr>" + "<td>" + item.PostId + "</td>" + "<td>" + item.PostTitle + "</td>" + "<td>" + item.ShortPostContent + "</td>" + "<td>" + item.MetaDescription + "</td>" + "</tr>";
- $('#blogTable tbody').append(rows);
- });
- },
- error: function(data) {}
- });
- });
- });
- </script>




Maria PrincePosted Feb 28, 2020, 7:46 AM
Thank you....
ahmidi mohamedPosted Sep 20, 2019, 7:44 AM
Null project databse Mauvais struct
Durgaprasad BoddapatiPosted Oct 29, 2018, 9:21 AM
This article is ok thanks c# corner group
bishoe nbPosted Dec 12, 2017, 12:18 PM
Thanks.............
Prasanna MuraliPosted Sep 5, 2016, 11:06 AM
Nice post......
RakeshPosted Sep 2, 2016, 1:54 AM
Good