After seeing a lot of code samples, I cant make a simple datatable using Jquery Datatables and MVC.
I got the error
My controller is this
public class DataTableController : Controller
{
// GET: DataTable
public ActionResult Index()
{
return View();
}
public ActionResult GetData()
{
var registros = new List<PruebaClass>();
var pruebaClass1 = new PruebaClass
{
Race = "Aliens",
Year = 1990,
Total = 50
};
var pruebaClass2 = new PruebaClass
{
Race = "MArcianos",
Year = 200,
Total = 20
};
registros.Add(pruebaClass1);
registros.Add(pruebaClass2);
var resultado = Json(new { aaData = registros.ToList() }, JsonRequestBehavior.AllowGet);
return resultado;
}
public class PruebaClass
{
public string Race { get; set; }
public int Year { get; set; }
public int Total { get; set; }
}
}
My view is this
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<table id="miTable">
<thead>
<tr>
<th>Race</th>
<th>Year</th>
<th>Total</th>
</tr>
</thead>
</table>
@section Scripts{
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/css/jquery.dataTables_themeroller.css">
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="~/Scripts/MyDataTablejs.js"></script>
}
And my javascript file is this
$(document).ready(function () {
$('#miTable').DataTable(
{
"sAjaxSource": "../DataTable/GetData",
"columns": [
{ "Data": "Race", "autoWidth": true },
{ "Data": "Year", "autoWidth": true },
{ "Data": "Total", "autoWidth": true }
]
});
});
I can reach the ActionResult, and my view shows two rows but the content of each cell is null. And I got the awfull error Datatables warning (table id= 'miTable')Requested unknown parameter '0' from the datasource '0' .
Im pretty sure that the problem is the source (maybe the JSON format) and the column name mapping, but I cant figure out what is. Any help?
"Data": 0
,"Data": 1
etc. You may still have problems because you're not returning any rowcount values for the datatable to use, but let's deal with the first error.