开发者

List of objects to JSON to Html Table?

开发者 https://www.devze.com 2022-12-24 07:42 出处:网络
If I have a list of objects IEnumerable<MyType> myTypes; Is it possible for me to return this to the client as JSON

If I have a list of objects

IEnumerable<MyType> myTypes;

Is it possible for me to return this to the client as JSON

return Json(myTypes);

and if so, is it possible for me to convert this (now JSON format) list to a <table> when it gets to the client?

Is there any jQuery plugin t开发者_如何学Goo do this?

The thing is, there's loads of other stuff I need to send as JSON also, so generating a table with a PartialView and embedding that into the JSON is a extra complexity that I'd like to avoid.


I came up with my own solution for a similar problem, I wanted to be able to display any JSON object array response into a nice table without having to hard code anything in the JavaScript so it was reusable!

Here is what I did...

<script type="text/javascript">
    $(document).ready(function() {
        $.ajax({
            type: "POST",
            url: "DemoSvc.asmx/GetJSONTableContents",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: "{}",
            success: function(res) {
                $('#<%= DynamicGridLoading.ClientID %>').hide();
                $('#<%= DynamicGrid.ClientID %>').append(CreateDynamicTable(res.d)).fadeIn();
            }
        });
    });
</script>

This is doing the pulling of data from the web service to the page, the important part of this code is the call to the "CreateDynamicTable()" that converts the JSON object array to a pretty HTML table. Below is the code, the output is a pretty table of HTML.

function CreateDynamicTable(objArray) {
  var array = JSON.parse(objArray);

  var str = '<table class="lightPro">';
  str += '<tr>';
  for (var index in array[0]) {
    str += '<th scope="col">' + index + '</th>';
  }
  str += '</tr>';
  str += '<tbody>';
  for (var i = 0; i < array.length; i++) {
    str += (i % 2 == 0) ? '<tr class="alt">' : '<tr>';
    for (var index in array[i]) {
      str += '<td>' + array[i][index] + '</td>';
    }
    str += '</tr>';
  }
  str += '</tbody>'
  str += '</table>';
  return str;
}

I also looked for something FREE to do this, but everything I found was commercial or required hard coding column values. I did a quick blog post with additional details, screen shot and a simple VS 2008 demo. Overall, it's working perfect for what I needed.

Blog Article on JSON data to HTML Table


It's not an HTML table, exactly, but I use jqGrid along with Craig Stuntz's helper functions to "export" any IQueryable<T> as JSON. The helper function ToJqGridData sends JSON in exactly the format required by jqGrid, so your code is nice and neat:

MyObjectRepository rep = new MyObjectRepository();
var myObjects = from o in rep.SelectAll()
                select new 
                {
                    Prop1 = o.Prop1,
                    Prop2 = o.Prop2
                    ...
                }
return Json(apps.ToJqGridData(page, rows, sidx, null, null), JsonRequestBehavior.AllowGet);

Be aware you'll also need to update the global settings for your jqGrids to make them compatible with the naming conventions used by ToJqGridData (I just include this script in my master page):

$(document).ready(function() {
    GridDemo.SiteMaster.setDefaults();
});

var GridDemo = {
    Home: {
        GridDemo: {}
    },
    SiteMaster: {
        setDefaults: function() {
            $.jgrid.defaults = $.extend($.jgrid.defaults, {
                datatype: 'json',
                height: 'auto',
                imgpath: '/Scripts/jqGrid/themes/lightness/images',
                jsonReader: {
                    root: "Rows",
                    page: "Page",
                    total: "Total",
                    records: "Records",
                    repeatitems: false,
                    userdata: "UserData",
                    id: "Id"
                },
                loadui: "block",
                mtype: 'GET',
                multiboxonly: true,
                rowNum: 20,
                rowList: [10, 20, 50],
                viewrecords: true
            });
        }
    }
};
0

精彩评论

暂无评论...
验证码 换一张
取 消