我正在使用数据表从数据库中获取数据。我面临的问题是获取数据的控制器方法正常工作并返回DataSet,我可以在xhr中看到但数据没有显示在html页面中。我无法弄清楚问题所在。在这方面的任何帮助将不胜感激。 这是我的代码段。
<table id="DbTable">
<thead>
<tr>
<th >ID</th>
<th>Name</th>
<th>E-mail</th>
<th>Address</th>
</tr>
</thead>
</table>
脚本代码:
$(document).ready(function () {
$.ajax({
url: '@Url.Action("GetCompanies", "Company")',
method: 'get',
dataType: 'json',
success: function (data) {
$('#DbTable').DataTable({
data: data,
columns: [
{ "data": "Id" },
{ "data": "Name" },
{ "data": "Email" },
{ "data": "Address" },
]
});
}
});
});
这是控制器代码:
[HttpGet]
public JsonResult GetCompanies()
{
try
{
IEnumerable<Company> company = _companyService.GetCompanies().ToList();
IEnumerable<CompanyListViewModel> viewModelListCompanies = Mapper.DynamicMap<IEnumerable<Company>, IEnumerable<CompanyListViewModel>>(company);
return new JsonSuccessResult(viewModelListCompanies);
}
catch (Exception ex)
{
Response.StatusCode = (int)ResponseCode.UnprocessableEntity;
return new JsonErrorResult(ex.ToString());
}
}
JsonSuccessResult类:
public class JsonSuccessResult : JsonResult
{
public JsonSuccessResult()
{
Data = new { Success = true, Error = false, Message = "Data has been saved successfully" };
ContentEncoding = System.Text.Encoding.UTF8;
JsonRequestBehavior = JsonRequestBehavior.AllowGet;
}
public JsonSuccessResult(MessageCode messageCode)
{
Data = new { Success = true, Error = false, Message = MessageDictionary.SuccessMessages[messageCode] };
ContentEncoding = System.Text.Encoding.UTF8;
JsonRequestBehavior = JsonRequestBehavior.AllowGet;
}
public JsonSuccessResult(string message)
{
Data = new { Success = true, Error = false, Message = message };
ContentEncoding = System.Text.Encoding.UTF8;
JsonRequestBehavior = JsonRequestBehavior.AllowGet;
}
public JsonSuccessResult(IEnumerable enumerable, long totalCount = 0, int limit = 50, int offset = 0)
{
Data = new
{
Success = true,
Error = false,
Message = "Success",
DataSet = enumerable,
Limit = limit,
Offset = offset,
TotalCount = totalCount,
};
ContentEncoding = System.Text.Encoding.UTF8;
JsonRequestBehavior = JsonRequestBehavior.AllowGet;
}
public JsonSuccessResult(object data)
{
Data = new
{
Success = true,
Error = false,
Message = "Success",
Data = data
};
ContentEncoding = System.Text.Encoding.UTF8;
JsonRequestBehavior = JsonRequestBehavior.AllowGet;
}
public JsonSuccessResult(int val)
{
Data = new
{
Success = true,
Error = false,
Message = "Success",
Data = val
};
ContentEncoding = System.Text.Encoding.UTF8;
JsonRequestBehavior = JsonRequestBehavior.AllowGet;
}
}
答案 0 :(得分:1)
您返回的JsonSuccessResult
对象不是数组,它是一个对象,其中包含名为DataSet
的属性中的数据。所以你需要改变
success: function (data) {
$('#DbTable').DataTable({
data: data,
到
success: function (data) {
$('#DbTable').DataTable({
data: data.DataSet,