I want to show table data using Ajax request.
Here is my Ajax Syntax:
$(document).ready(function() {
var table = $("#attendance").DataTable({
ajax: {
url: '@Url.Action("GetAttendance", new {id = Model.Student.Id})',
dataSrc: ""
},
columns: [
{
data: "Date",
render: function(data) {
return data;
}
},
{
data: "Status.StudentStatus",
render: function(data) {
return data;
}
}
]
});
Here is my action method:
public JsonResult GetAttendance(int id)
{
var studentAttendance = _context.Attendances.ToList().Where(m => m.StudentId == id);
return Json(studentAttendance, JsonRequestBehavior.AllowGet);
}
Now, where am I wrong?
Please plug in the following example. If you don't mind, please just follow my example, and then you will be able to fix your issue.
Controller/Model:
public class AjaxViewModel
{
public string theDate { get; set; }
public string StudentStatue { get; set; }
}
public class HomeController : Controller
{
public string GetAttendance()
{
AjaxViewModel aViewModel = new AjaxViewModel { StudentStatue = "stat4", theDate = "12/24/2005" };
AjaxViewModel aViewModel2 = new AjaxViewModel { StudentStatue = "stat5", theDate = "12/24/2005" };
AjaxViewModel aViewModel3 = new AjaxViewModel { StudentStatue = "stat6", theDate = "12/24/2005" };
IList<AjaxViewModel> data = new List<AjaxViewModel>();
data.Add(aViewModel);
data.Add(aViewModel2);
data.Add(aViewModel3);
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(data);
json = "{ \"data\": " + json;
json = json + " }";
return json;
}
View:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index2020</title>
<script src="~/Scripts/jquery-1.12.4.min.js"></script>
<link href="~/Content/DataTables/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="~/Scripts/DataTables/jquery.dataTables.min.js"></script>
<script type="text/javascript">
$(function () {
$("#uiDataTable").DataTable({
"ajax": '@Url.Action("GetAttendance")',
columns: [
{
"data": "theDate"
},
{
"data": "StudentStatue"
}
]
});
})
</script>
</head>
<body>
<table id="uiDataTable" class="display table table-striped table-bordered">
<thead>
<tr>
<th>
Date
</th>
<th>
Status
</th>
</tr>
</thead>
</table>
</body>
</html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.