Wednesday, 29 August 2012

Passing data from an MVC Controller to a View using JSON, javascript :

To get started I will use a new MVC project...   goal is to pass information (which could have come from a SQL database) from the controller to the view...  When the view receives the data it will parse it and create a simple html table.  Here is the data:



And with in the project in my Home Xontrolle added a new method as follows:


public ActionResult GetJSONData()
        {
            // Create a JSON document setting the string array to the count of the rows
            var Customers = new {
                Name = new string[2],
                Address = new string[2],
                Phone = new string[2]
            };

            // Add data to it (you would likely do this in a loop or a SQL data reader)
            Customers.Name[0] = "Anks";
            Customers.Name[1] = "Pruthvi";
            Customers.Address[0] = "123 New St";
            Customers.Address[1] = "987 King St";
            Customers.Phone[0] = "123-123-1234";
            Customers.Phone[1] = "9885693216";

            // Return the JSON document to the view
            return Json(Customers);
        }

 And In My script File which is added in my script Folder used this following script :

<script type="text/javascript">

    var url = '/home/GetJSONData';
    $.post(url,
            null,
            function (data) {
                var i = 0;
                // Iterate through the JSON array
                var htmlString = "<table><thead><th>Names</th><th>Address</th><th>Phone</th></thead>"

                while (data.Name[i] != null) {
                    htmlString += "<tr>";
                    htmlString += "<td>" + data.Name[i] + "</td>";
                    htmlString += "<td>" + data.Address[i] + "</td>";
                    htmlString += "<td>" + data.Phone[i] + "</td>";
                    htmlString += "</tr>";
                    i++;
                }

                htmlString += "</table>"

                //Apply the html to a div
                document.getElementById("Customers").innerHTML = htmlString;
            }
        );

</script>



 And now in my view i'm giving that Customers as ID to a div now it'll done shows the table view of json data  in that appropriate as image shown above ..

No comments:

Post a Comment