Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Use the <code>System.Web.Script.Serialization.JavaScriptSerializer</code> class. It was specifically provided for JSON serialization.</p> <pre><code>using System.Web.Script.Serialization; public string ToJson(object o) { JavaScriptSerializer serializer = new JavaScriptSerializer(); return serializer.Serialize(o); } </code></pre> <p><b>EDIT</b>: Oops, I missed that your plugin doesn't want a true JSON representation of the objects; it just wants arrays of values. You could use reflection to iterate over the properties of the objects as others have suggested, but then you have no control over which properties end up in which columns. It is not clear from your question whether that is a problem for you.</p> <p>If you need a strict mapping between properties and columns, then you will have to define that somehow in C#. To do this you could implement <code>IEnumerable</code> as Ed demonstrates or create a custom interface:</p> <pre><code>public interface ITableDataSource { IList&lt;string&gt; GetTableData(); } </code></pre> <p>Then implement this on any objects that might need to be data sources for the jQuery table plugin:</p> <pre><code>public class Car : ITableDataSource { //...class implementation details... public IList&lt;string&gt; GetTableData() { return new List&lt;string&gt;() { this.Color, this.EngineSize, this.NumberOfSeats.ToString() }; } } </code></pre> <p>Finally, in your method that is returning the data to the jQuery plugin, use the interface to construct your response object, then pass it to my <code>ToJson()</code> method to serialize it:</p> <pre><code>public string DoSomething(IList&lt;ITableDataSource&gt; objects) { var result = new { sEcho = 1, iTotalRecords = 1, iTotalDisplayRecords = 1, aaData = new List&lt;IList&lt;string&gt;&gt;() }; foreach (ITableDataSource ds in objects) result.aaData.Add(ds.GetTableData()); return ToJson(result); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload