Creating Json File And Searching Data From Json File Using JavaScript

This is in addition to my article CRUD in single View. You can find the details of the class library, which I had used here.
 
For creating a JSON file, create a simple MVC project.
  1. Add a Contoller to your project.
  2. Add an ActionResult method, named as Index in your controller.
  3. Now, add a view to the Index and do the following steps in your view.
  1. @model IEnumerable<JsonEntity.Users>  
  2. //JsonEntity is my Class library whose reference is added to my project  
  3. //Users is my Model which i had added to my class library   
  4. @{  
  5.     ViewBag.Title = "Index";  
  6. }  
  7.   
  8. <h2>Index</h2>  
  9. <script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>  
  10. <p>  
  11.    <input type="button" id="btnCreateJson" value="Create Json"  class="btn btn-default"/>         
  12. </p>  
Now, add JavaScript.
  1. $("#btnCreateJson").click(function () {  
  2.         $.post("/Users/CreateJson"function (response) {  //Users is my controller's Name and CreateJson is my Jsonresult Method
  3.             if (response != null) {                
  4.                 alert("Json Created");  
  5.                 location.reload();  
  6.             }  
  7.             else {  
  8.                 alert("Error");  
  9.             }  
  10.         });  
  11.     })  
Add JsonResult Method to your controller, as given below:
  1. [HttpPost]  
  2.         public ActionResult CreateJson()  
  3.         {  
  4.             try  
  5.             {  
  6.                 using (JsonContext context = new JsonContext())       //JsonContext is my context name which i had used in class library  
  7.                 {  
  8.                     var UsersList = context.ObjUser.ToList();             // Getting the list of users for DB.  
  9.                     var jsondata = new JavaScriptSerializer().Serialize(UsersList);  
  10.                     string path = Server.MapPath("~/Json/");             //Path where your json file will be saved  
  11.                     System.IO.File.WriteAllText(path + "User.json", jsondata);            // User.json is your json file's name  
  12.                     return Json(UsersList, JsonRequestBehaviour.AllowGet);  
  13.                 }  
  14.             }  
  15.             catch(Exception ez)  
  16.             {  
  17.                 return null;  
  18.             }  
  19.         }    
Now, your JSON file has been created. For retrieving whole data from JSON file, write the code, given below:.
  1. $('#get-data').click(function () {           //get-data will be the id of your button  
  2.             var url="/Json/User.json";  
  3.             $.getJSON(url, function (data) {   //this method gets the json file and fetches the data inside it  
  4.                 console.log(data);               
  5.                 $('#show-data').empty(); //show-data is the id of div  
  6.   
  7.                 if (data.length) {  
  8.                     var content="<table class='table'>";  
  9.                     for(var i=0;i<data.length;i++)  
  10.                     {  
  11.                         content+="<tr><td>"+data[i].Name+"</td><td>"+data[i].Address+"</td><td>"+data[i].Phone_Number+"</td></tr>";                                                
  12.                     }  
  13.                     content+="</table>";  
  14.                     $('#show-data').append(content);  //this is to append the data fetched from json to the table  
  15.                 }  
  16.             });  
  17.   
  18.             showData.text('Loading the JSON file.');  
  19.     })  
For searching the users from JSON file, add a TextBox in your Index view.
  1. <input type="text" id="Search"  placeholder="Enter data"/>  
Here, I am adding a KeyUp function of JavaScript, as I want to search the data as soon as the alphabet is typed from the keyboard.
  1. $("#Search").keyup(function (e) {  
  2.        clearTimeout($.data(this'timer'));  
  3.        if (e.keyCode == 13)  
  4.            DataFromJson(true);  
  5.        else  
  6.            $(this).data('timer', setTimeout(DataFromJson, 50));     //sets the timer between the key press from keyboard and the search   
  7.    })  
  1. function DataFromJson(force)  
  2.    {          
  3.        var event = $("#Search").val();        //fetching the value from the textbox  
  4.            var url = "/Json/User.json";         //path where Json file is saved in my project  
  5.            $.getJSON(url, function (response) {  
  6.                //console.log(response);  
  7.                if (response.length) {  
  8.                    $("#tableUser").empty();        //tableUser is the id of the table  
  9.                    var content = "<tr><th>Name</th><th>Address</th><th>Phone Number</th></tr>";  
  10.                    for (var i = 0; i < response.length; i++) {  
  11.                        if ((response[i].Name).indexOf(event) != -1 || (response[i].Address).indexOf(event) != -1 || (response[i].Phone_Number).indexOf(event) != -1) //Name , Address and Phone_number are my attributes in User Table {  
  12.                            content += "<tr id='TableData'><td>" + response[i].Name + "</td><td>" + response[i].Address + "</td><td>" + response[i].Phone_Number + "</td></tr>";  
  13.                        }  
  14.                    }  
  15.                    $("#tableUser").append(content); //appending the list to the table  
  16.                }  
  17.            });          
  18.    }  
That's it. You can create and retrieve the data from JSON file. Searching is done without and page loads with the single alpha matching.
Ebook Download
View all
Learn
View all