Save And Bind Data Through JSON File In ASP.NET

Introduction

This article explains how to save data in JSON file and bind it instead of querying from database.
 
Advantages
 
JSON is platform independent. Getting data from Database and bind it to front end is ok but it opens a connection and connection pull size is limited depending upon your server configuration and processor. A website may be down if we are binding front-end data through direct querying because of limited connection pull size. You can get brief idea about JSON file and how it works from the following link.
 
Description
 
The following is the process of saving data in JSON file and binding it in front-end. Here I have used,
  1. ASP.NET MVC 4
  2. MSSQL 2008 as Database.
  3. Entity Framework code first approach.
  4. From nuget added reference Newtonsoft.json and entity framework.

Step 1: Open Visual studio  2013, click New Project.

Under Installed, Templates, Visual C#, click Web and provide the name and click OK as per the following image.
 
 
 
Step 2: After this a window will pop up from Template, select Empty and then select MVC as in the following screenshot,
 
 
 
Step 3: After this point from solution explore click on Solution, Add, then New Project as in the following image,
 
 
 
Step 4: After this a window will pop up, click Installed, Visual C#, then Class Library as in the following image and click OK,
 
 
 
Step 5: Now Rename the Class1 name to Instagram under JsonEntity and write the following code,
  1. public class Instagram  
  2. {  
  3.      [Key] //using System.ComponentModel.DataAnnotations;  
  4.      public int Id { getset; } // if we will write InstagramId instead of Id [Key] is not required  
  5.      public string InstagramId { getset; }  
  6.      public string Text { getset; }  
  7.      public string MediaSharedeUrl { getset; }  
  8.      public string UserName { getset; }  
  9.      public string LinkUrl { getset; }  
  10.      public string MediaType { getset; }  
  11.      public DateTime CreateDate { getset; }  
  12.      public DateTime ModifyDate { getset; }  
  13.      public string Status { getset; }  
  14. }
 After this Add EntityFramework from Manage NuGet Packages for solution as in the following images,
 
 
 
 
After this add a new folder with name Context and add a class with name JsonContext (The class has to be public) as in the following image,
 
 
 
Step 6: After this add the following code in the JsonContext.cs class,
  1. public class JsonContext : DbContext //using System.Data.Entity;  
  2.    {  
  3.        public DbSet<Instagram> ObjInstagramDatas { getset; }    
  4.    } 
Now in the web.config of the DemoJson project add the following code to create database and table.
  1. <connectionStrings>  
  2.    <add name="JsonContext" connectionString="Data Source=(local); Initial Catalog=JsonDemo; User Id=sa; Password=Admin@321" providerName="System.Data.SqlClient"/>  
  3.  </connectionStrings>   
Note:
  • Here in name I have added "JsonContext", it has to be as per context class name and Initial Catalog=JsonDemo. It will create a database JsonDemo if it do not exist.
Now build the solution and provide the dll reference of the class in the DemoJson Project. And this completes the entity framework code first approach.
 
Step 7: I have taken a Controller called Home and added the following code and find the comments for better understanding. Also I have added Newtonsoft.json from Manage NuGet Packages for solution.
  1. public class HomeController : Controller    
  2. {    
  3.     // GET: Home    
  4.     public ActionResult Index()    
  5.     {    
  6.         if (!Directory.Exists(Server.MapPath("~/JsonData")))    
  7.         {    
  8.             Directory.CreateDirectory(Server.MapPath("~/JsonData"));    
  9.             System.IO.File.WriteAllText(Server.MapPath("~/JsonData/InstagramData.json"), null);    
  10.         }  
  11.         var jsonInstagramdata = new StreamReader(Server.MapPath("~/JsonData/InstagramData.json"));    
  12.         var rawJsonData = jsonInstagramdata.ReadToEnd();    
  13.         jsonInstagramdata.Close();    
  14.         var dtlData = JsonConvert.DeserializeObject<List<Instagram>>(rawJsonData); //Get List Of all Data Json File    
  15.         if (dtlData != null)    
  16.         {    
  17.             ViewData["InstagramData"] = dtlData.ToList();    
  18.         }    
  19.         return View();    
  20.     }    
  21.     public ActionResult ReadInstagramRecord()  //This is used to get Instagram records and save data in database.    
  22.     {    
  23.         var count = 0;    
  24.         try    
  25.         {    
  26.             const string hashtag = "ProudToBeIndian"//getting data from hash tag    
  27.             const string accessToken = "16741082.1b07669.121a338d0cbe4ff6a5e04543158a4f82";    
  28.             var request = (HttpWebRequest)WebRequest.Create("https://api.instagram.com/v1/tags/" + hashtag + "/media/recent?count=33&access_token=" + accessToken + ""); //Hiting API    
  29.             request.Method = "GET";    
  30.             using (var response = (HttpWebResponse)request.GetResponse()) //Saving the json response in database    
  31.             {    
  32.                 var dataStream = response.GetResponseStream();    
  33.                 var reader = new StreamReader(dataStream);    
  34.                 var json = reader.ReadToEnd();    
  35.                 dynamic instagramDataList = JsonConvert.DeserializeObject(json);    
  36.                 foreach (var data in instagramDataList.data)    
  37.                 {    
  38.                     using (var context = new JsonContext()) //Inserting the user details into Db    
  39.                     {    
  40.                         var instagramData = new Instagram();    
  41.   
  42.                         string img = data.type == "image" ? data.images.standard_resolution.url : data.videos.standard_resolution.url;    
  43.                         instagramData.Text = data.caption.text;    
  44.                         instagramData.InstagramId = data.id;    
  45.                         instagramData.UserName = "https://www.instagram.com/" + data.user.username;    
  46.                         instagramData.CreateDate = DateTime.Now;    
  47.                         instagramData.ModifyDate = DateTime.Now;    
  48.                         instagramData.Status = "Approved";    
  49.                         instagramData.MediaType = data.type;    
  50.                         instagramData.MediaSharedeUrl = img;    
  51.                         instagramData.LinkUrl = data.link;    
  52.                         var qry = (from s in context.ObjInstagramDatas where s.InstagramId == instagramData.InstagramId select s).FirstOrDefault();    
  53.                         if (qry != nullcontinue;    
  54.                         context.ObjInstagramDatas.Add(instagramData);    
  55.                         context.SaveChanges();    
  56.                         count++;    
  57.                     }    
  58.                 }    
  59.   
  60.                 reader.Close();    
  61.                 if (dataStream != null) dataStream.Close();    
  62.             }    
  63.             ViewBag.CountData = count;    
  64.             return RedirectToAction("Index");    
  65.         }    
  66.         catch (Exception ex)    
  67.         {    
  68.             ViewBag.ErrorMessage = "Some exception occured" + ex;    
  69.             return View("Index");    
  70.         }    
  71.     }    
  72.   
  73.     public ActionResult UpdateJson() //Getting data from database and save in Json File    
  74.     {    
  75.         using (var context = new JsonContext())    
  76.         {    
  77.             try    
  78.             {    
  79.                 var getInstaData = context.ObjInstagramDatas.Where(x => x.Status == "Approved").ToList();    
  80.                 var selectInstaData = getInstaData.AsEnumerable().Where(x => x.Status == "Approved").Select((obj, index) => new Instagram()    
  81.                 {    
  82.                     Text = obj.Text,    
  83.                     MediaSharedeUrl = obj.MediaSharedeUrl,    
  84.                     MediaType = obj.MediaType,    
  85.                     Status = obj.Status,    
  86.                     CreateDate = obj.CreateDate,    
  87.                     ModifyDate = obj.ModifyDate,    
  88.                     LinkUrl = obj.LinkUrl,    
  89.                     UserName = obj.UserName,    
  90.                     Id = index + 1    
  91.                 });    
  92.                 var bindInstaData = selectInstaData.ToList();    
  93.   
  94.                 var jsonString = JsonConvert.SerializeObject(bindInstaData);    
  95.                 if (jsonString != null)    
  96.                 {    
  97.                     if (!Directory.Exists(Server.MapPath("~/JsonData")))    
  98.                     {    
  99.                         Directory.CreateDirectory(Server.MapPath("~/JsonData"));    
  100.                     }    
  101.                 }    
  102.                 System.IO.File.WriteAllText(Server.MapPath("~/JsonData/InstagramData.json"), jsonString);    
  103.                 return RedirectToAction("Index");    
  104.             }    
  105.             catch (Exception)    
  106.             {    
  107.                 throw;    
  108.             }    
  109.         }    
  110.     }    
  111. }   
Step 8: View for Index page design is as follows:
  1. @using JsonEntity  
  2. @{  
  3.     Layout = null;  
  4.     var data = ViewData["InstagramData"];  
  5. }  
  6.   
  7. <!DOCTYPE html>  
  8.   
  9. <html>  
  10. <head>  
  11.     <meta name="viewport" content="width=device-width" />  
  12.     <title>Json Demo</title>  
  13.     <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.10/css/jquery.dataTables.min.css" />  
  14.     <script language="JavaScript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>  
  15. </head>  
  16. <body>  
  17.     <div class="col-lg-offset-3 col-md-9">  
  18.         <h4>@Html.ActionLink("Index", "Index", "Home", null, new { @class = "btn btn-success" })    @Html.ActionLink("Fetch Data", "ReadInstagramRecord", "Home", null, new { @class = "btn btn-primary" })     @Html.ActionLink("Update Json", "UpdateJson", "Home", null, new { @class = "btn btn-primary" })</h4>  
  19.     </div>  
  20.     <div>  
  21.         <table id="example" class="display" cellspacing="0" width="100%">  
  22.             <thead>  
  23.                 <tr>  
  24.                     <th>Id</th>  
  25.                     <th>Media Shared Url</th>  
  26.                     <th>Media Type</th>  
  27.                     <th>Text</th>  
  28.                     <th>Status</th>  
  29.                 </tr>  
  30.             </thead>  
  31.             <tbody>  
  32.                 @if (data == null)  
  33.                 {  
  34.                     <tr>  
  35.                         <td>  
  36.                             No records to show  
  37.                         </td>  
  38.                     </tr>  
  39.                 }  
  40.                 else  
  41.                 {  
  42.                     foreach (var item in (List<Instagram>)data)  
  43.                     {  
  44.                         <tr>  
  45.                             <td>  
  46.                                 @item.Id  
  47.                             </td>  
  48.                             <td>  
  49.                                 @if (item.MediaSharedeUrl != null)  
  50.                                 {  
  51.                                     if (item.MediaType == "image")  
  52.                                     {  
  53.                                         <a href="@item.MediaSharedeUrl" target="_blank">View Image</a>  
  54.                                     }  
  55.                                     else  
  56.                                     {  
  57.                                         <a href="@item.MediaSharedeUrl" target="_blank">View Video</a>  
  58.                                     }  
  59.                                 }  
  60.                                 else  
  61.                                 {  
  62.                                     <span>Not Available</span>  
  63.                                 }  
  64.                                 @*<img src="@item.MediaSharedeUrl" style="height:50px;width:50px; " class="img-circle" />*@  
  65.                             </td>  
  66.                             <td>  
  67.                                 @item.MediaType  
  68.                             </td>  
  69.                             <td>  
  70.                                 @item.Text  
  71.                             </td>  
  72.                             <td>  
  73.                                 @item.Status  
  74.                             </td>  
  75.                             @*<td>  
  76.                         <input type="checkbox" class="chcktblInsta" name="chcktblInsta" value="@item.Id" />  
  77.                     </td>*@  
  78.                         </tr>  
  79.                     }  
  80.                 }  
  81.             </tbody>  
  82.         </table>  
  83.     </div>  
  84.   
  85.     <script type="text/javascript">  
  86.         $(document).ready(function () {  
  87.             $('#example').DataTable();  
  88.         });  
  89.     </script>  
  90.     <script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>  
  91.     <script type="text/javascript" src="https://cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js"></script>  
  92. </body>  
  93. </html> 
You can download the sample project from the Google Drive link.

Up Next
    Ebook Download
    View all
    Learn
    View all