Search code examples
jsonasp.net-mvc-3viewdata

Read retrieved json data using jquery in View mvc 3


I declared and serialized data on my View page

@model IEnumerable<MVCvs2012.Models.Employees>

 @{
    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    var employees = @serializer.Serialize(ViewData["Employees"]);   
  }

Results when running the browser:

[{"FirstName":"Nancy","LastName":"Davolio","Title":"Sales Representative"}]

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>
</tr>
...
</table>

Solution

  • Use jQuery.each to build your table. Something along the lines of

    $var table = '<table>';
    $.each(yourJson, function( index, value ) {
          $table += '<tr><td>' + value.FirstName + '</td><td>' + ...
    });
    $table += '</table>';