【发布时间】:2011-12-30 15:07:15
【问题描述】:
我有一个带有 JQuery DataTable 的视图,它通过调用一个动作方法(服务器端处理)通过 AJAX 加载它的内容,该方法返回一个带有所有数据的漂亮 JSON 字符串。
我正在做的事情如下:
- 我创建了一个包含 DataTable 数据的列表。表中的每一行都是一个字符串数组,因为这是 DataTables 的要求。
- 我将 DataTable 的所有数据放在一个匿名对象中。此数据由行数、数据(列表)和其他一些内容组成。
- 从这个匿名对象创建一个 JSON 字符串,因此所有数据都以 JSON 格式返回
- 发生了一些神奇的事情,数据显示在我的 DataTable 中。
问题是:我无法输出 HTML,因为 Razor 会自动转义它。我已经尝试过 Html.Raw、new HtmlString() 之类的东西,但问题是:我必须将 HTML 字符串放入我的 List 集合中,因为据我所知,DataTables 无法处理任何其他类型。
在我看来,DataTable 不包含应呈现哪些列的任何定义,这是通过循环我的 JSON 字符串(使用 Javascript 或其他)并显示它(再次使用 Javascript)自动完成的。
所以问题是:使用 MVC3 服务器端处理时,如何在 DataTable 中呈现 HTML?
顺便说一句,代码:
<table id="datatable">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Destination address</th>
<th>Platform</th>
<th> </th>
<th> </th>
</tr>
</thead>
<tbody id="tabledata">
<!-- Content will be rendered here by AJAX -->
</tbody>
<tfoot>
<tr>
<th>Id</th>
<th>Name</th>
<th>Destination address</th>
<th>Platform</th>
<th> </th>
<th> </th>
</tr>
</tfoot>
</table>
以及服务器端处理:
public JsonResult List()
{
List<PushApplication> pushApplications = _service.GetData(Request).ToList();
int totalRecords = _service.GetApplicationCount();
// Reformat the data.
List<string[]> aaData = new List<string[]>(pushApplications.Count);
aaData.AddRange(pushApplications.Select(application => new[]
{
application.Id.ToString(),
application.Name,
application.DestinationAddress,
application.Platform,
"<a href='/PushApplication/Edit/" + application.Id + "'>Modify</a>",
"<a href='/PushApplication/Delete/" + application.Id + "'>Delete</a>"
}));
// Construct anonymous object for the data table.
var data = new { sEcho = Request.QueryString["sEcho"], iTotalRecords = totalRecords, iTotalDisplayRecords = totalRecords, aaData = aaData };
return Json(data, JsonRequestBehavior.AllowGet);
}
我使用以下 Javascript 调用数据表:
$(document).ready(function () {
var oTable = $('#datatable').dataTable({
"bPaginate": true,
"bLengthChange": true,
"bFilter": true,
"bSort": true,
"bInfo": true,
"bAutoWidth": false,
"bProcessing": true,
"bServerSide": true,
"bJQueryUI": true,
"iDisplayStart": 0,
"sEcho": 1,
"sDom": 'T<"clear"><"top"fi>rt<"bottom"pl><"clear">',
"sAjaxSource": '/PushApplication/List',
"sPaginationType": "full_numbers",
"fnServerData": fnDataTablesPipeline,
"oTableTools": {
"sSwfPath": "/Plugins/TableTools/swf/copy_cvs_xls_pdf.swf"
},
"aoColumns": [
{ sWidth: '10%' },
{ sWidth: '30%' },
{ sWidth: '30%' },
{ sWidth: '30%' }
]
});
$("#submitForm").click(function () {
oTable.fnDraw();
});
});
【问题讨论】:
-
你也可以发布一些javascript代码
-
好吧,魔术是由 JQuery DataTables 完成的,我唯一要做的就是在我的 HTML 中包含该库,并且 将自动填充数据。老实说,我不知道> 7000行代码文件的哪一部分负责呈现数据。然而,我已经发布了调用 JQuery DataTable 的 javascript 代码。
标签: jquery asp.net asp.net-mvc-3 razor datatables