Reputation: 327
I have the following data in an array.
[{"FirstName":"Nancy","LastName":"Davolio","Title":"Sales Representative"},
{"FirstName":"Andrew","LastName":"Fuller","Title":"Vice President, Sales"}]
I want to present this data using jquery into a table like this :
<table id="employee">
<tr>
<td>Nancy</td>
<td>Davolio</td>
<td>Sales Representative</td>
...
</table>
Upvotes: 3
Views: 2839
Reputation: 5685
it is understood that for simple ops like this, manually assemble DOM is okay. But I am still a bit surprised that no one mentioned jquery templating.
see details from this link: Jquery Template, With below contents cited there.
The plugin parses a template using data attributes to populate the data. Simply pass in a JavaScript object, and the plugin does the rest.
An example template is below:
<script type="text/html" id="template">
<div data-content="author"></div>
<div data-content="date"></div>
<img data-src="authorPicture" data-alt="author"/>
<div data-content="post"></div> </script>
And to use this do the following:
$("#template-container").loadTemplate($("#template"),
{
author: 'Joe Bloggs',
date: '25th May 2013',
authorPicture: 'Authors/JoeBloggs.jpg',
post: 'This is the contents of my post'
});
Similarly the content of the template could be held in a separate html file without the enclosing script tag, and used like the following:
$("#template-container").loadTemplate("Templates/template.html",
{
author: 'Joe Bloggs',
date: '25th May 2013',
authorPicture: 'Authors/JoeBloggs.jpg',
post: 'This is the contents of my post'
});
The plugin has a number of data-... attributes that can be used to populate various attributes with the data. There is also the powerful data-template-bind attribute that accepts a JSON object, enabling binding to any attribute, or the content of the element.
Upvotes: 0
Reputation: 1538
I don't believe you need jQuery for this. A foreach in razor should be enough. Something like this should work (given that the model passed is IEnumerable) :
<table id="employee">
@foreach (var employee in Model)
{
<tr>
<td>@employee.LastName</td>
<td>@employee.FirstName</td>
<td>@employee.TItle</td>
</tr>
}
</table>
Upvotes: 0
Reputation: 1546
similar
$(document).ready(function() {
var jsonp = '[{"Lang":"jQuery","ID":"1"},{"Lang":"C#","ID":"2"}]';
var lang = '';
var obj = $.parseJSON(jsonp);
$.each(obj, function() {
lang += this['Lang'] + "<br/>";
});
$('span').html(lang);
});
Upvotes: 6
Reputation: 1005
I did something like this before:
var apiUrl = 'UrlOfData';
$(document).ready(function () {
$.getJSON(apiUrl)
.done(function (data) {
for (var item in data){
$('#people').append(item.FirstName);
}
})
.fail(function (jqXHR, textStatus, err) {
$('#people').text('Error: ' + err);
});
});
Upvotes: 2