How can retrieve data from Json source and show them on the page?

Maybe it is very difficult for you to connect to the Json file and retrieve data, today I want to make it easy for you 🙂 Lets start.

Follow these steps:

  1. We need a Json file for the source that produces Json data for us. To make a Json file please follow these steps :
    1. Make a new  text file and copy this information to the file
"one": "Singular sensation",

"two": "Beady little eyes",

"three": "Little birds pitch by my doorstep"
    1. Change the file extension to the Json
    2. Now you have Json file that contains data , please copy the file in your project ( I assumed you are working in Visual studio )
    3. There two types of instructions that you can follow to read a Json file , Today I want to use $.getJSON (This a JQuery function)
<script>

    $(document).ready(function () {

        $.getJSON("Data/info.Json.", function (data) {
        var items = [];
        $.each(data, function (key, val) {
            items.push("<li id='" + key + "'>" + val + "</li>");
        });

        $("<H1>", {
            "class": "my-new-list",
            html: items.join("")
        }).appendTo("body");
    });
    })

</script>

GetJSON hast two parameters

  • Source of JSON , it could be URL or the address of JSON file
  • The function that gets data from JSON source

        $.getJSON("Data/info.Json.", function (data) {

4.  Then we should add data to the array


        $.each(data, function (key, val) {
            items.push("<li id='" + key + "'>" + val + "</li>");
        });

</script>

5.  And in the last step we should add the HTLM codes that we generated in the previous step to the body tag.


        $("<H1>", {
            "class": "my-new-list",
            html: items.join("")
        }).appendTo("body");
    });

And do not forget to add JQuery reference to your code , it coule be like this :

<script src="~/Scripts/jquery-ui-1.8.20.js"></script>
<script src="~/Scripts/jquery-1.7.1.js"></script>


Categories: .Net, ASP.Net, MVC

Tags: , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: