I am getting JSON result from my C# MVC controller into front end using Ajax call
{
"Profiles": [{
"CustomerName": "Ichiban Fish House",
"Distance": 4978.96
}, {
"CustomerName": "Dragonfly Bakery\u0026amp;Cafe",
"Distance": 4745.74
}, {
"CustomerName": "Roadside Country Diner The",
"Distance": 4336.64
}, {
"CustomerName": "Brock Stop The",
"Distance": 4336.64
}, {
"CustomerName": "Charcoal Cook House",
"Distance": 4336.64
}, {
"CustomerName": "Bayview Diner",
"Distance": 4286.19
}, {
"CustomerName": "Ridalco Industries Inc",
"Distance": 4286.19
}, {
"CustomerName": "Cartel Taco",
"Distance": 3396.05
}]
}
now i would like to loop through it and show Customer name and Distance in a table using jQuery.
here is the current code of HTML table
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>Customer Name</th>
<th>Distance(in km)</th>
</tr>
</thead>
<tbody id="TablBody">
</tbody>
</table>
How can i achieve this?
You can easily loop on your JSON data using jquery $.each(), so your code would be something like this
$.ajax({
url: "/Test/TestMethod",
type: 'GET',//type of request
success: function (data) {
//Check if Profiles have data using .length function
if (data.Profiles.length > 0) {
//Create a string to be appneded as html in table
var tableBody = "";
$.each(data.Profiles, function (i, item) {
tableBody = tableBody + "<tr><td>" + item.CustomerName + "</td><td>" + item.Distance + "</td></tr>";
});
//Show TablBody html as above created string
$("#TablBody").html(tableBody);
}
else
{
alert("No data")
}
},
error: function () {
alert("Error");
}
});
You can also use javascript for loop instead of $.each if needed, hope this helps.
You can also use the javascript approach, you can loop over the JSON Result array like this:
for(var i = 0; i < json.length; i++) {
var obj = json[i];
console.log(obj.Distance); // 4978.96
}
Or Suppose you multi-dimensional JSON result, you can loop it using jQuery like
$.each(data, function() {
$.each(this, function(k, v) {
// code here
});
});
If you have an array of objects/maps so the outer loop iterates over those. The inner loop iterates over the properties on each object element.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly