3

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>
zinking
  • 5,561
  • 5
  • 49
  • 81
Francis Padron
  • 307
  • 2
  • 7
  • 15
  • A bit more context and details would be welcomed. What are you trying to achieve? A sample of the view and backend code would be also great. – rivarolle Sep 26 '13 at 15:33
  • So my goal is, get the data from my controller using ViewData and put the retrieved values on View on just a click of a button using jquery and without refreshing the page, here is the backend code for my View: – Francis Padron Sep 26 '13 at 21:38
  • View:@{ var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); var employees = @serializer.Serialize(ViewData["Employees"]); } $("#employee").append("" + "@employees.toString" + "");-so basically I want to append the serialized data to my table which you can see from above. – Francis Padron Sep 26 '13 at 21:50
  • @Scott.N, what more do you want than the current supplied answer? – Dave Alperovich Oct 16 '13 at 21:11
  • I got this working using - $.ajax ( { url: 'http://localhost:32709/Emplyees/Get/', type: 'GET', datatype: 'json', success: function (data) { $.each ( data, function (key, employee) { $("#empTable").append("" + employee.FirstName + ""); } ); } } ); – Francis Padron Oct 21 '13 at 00:24

4 Answers4

6

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);
    });​
Mr.LamYahoo
  • 1,536
  • 13
  • 28
  • I declared my data using razor at my View page and used serialization '@model IEnumerable @{ var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); var employees = @serializer.Serialize(ViewData["Employees"]); }' – Francis Padron Sep 26 '13 at 16:36
  • This totally works . . . but the data of my jsonp is coming from a ViewData, can you please advise me on this one? please... – Francis Padron Sep 27 '13 at 03:23
  • 1
    var jsonp = '@ViewData["key"]'; – Mr.LamYahoo Sep 27 '13 at 03:27
  • Theres no data appending on my table var j = '@ViewData["Employees"]'; var json = $.parseJSON(j); $(json).each(function (i, val) { $.each(val, function (k, v) { $("#employee").append("" + k + " : " + v + ""); }); – Francis Padron Sep 27 '13 at 03:34
  • make sure @ViewData["Employees"] is a string with json format. You can try alert(j) to test before run function. – Mr.LamYahoo Sep 27 '13 at 03:44
  • This is what my alert is showing "System.Web.Mvc.JsonResult" and this is my code in my controller JsonResult o = Json(data, JsonRequestBehavior.AllowGet); ViewData["Employees"] = o; – Francis Padron Sep 27 '13 at 04:33
2

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);
        });
});
Daniel Dawes
  • 975
  • 5
  • 16
  • **bold**I declared my data using razor at my View page '@model IEnumerable @{ var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); var employees = @serializer.Serialize(ViewData["Employees"]); }' – Francis Padron Sep 26 '13 at 16:27
  • Don't use JavaScriptSerializer... it's kinda terrible. Try JSON.NET http://james.newtonking.com/json – gudatcomputers Oct 21 '13 at 19:03
0

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>
rivarolle
  • 1,528
  • 11
  • 18
  • So my goal is, get the data from my controller using ViewData and put the retrieved values on View on just a click of a button using jquery and without refreshing the page. – Francis Padron Sep 27 '13 at 01:54
0

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.

zinking
  • 5,561
  • 5
  • 49
  • 81