I’m trying to fetch my users list data into jQuery Datatable, but instead of data getting populated in my Datatable, it just returns a raw JSON format page with my data.
I have searched all over the internet mostly what is written in their solution I’m applying the same technique.
Here is my ASP.NET MVC action method:
[Route("Admin/Users")]
public ActionResult GetAllUsers()
{
List<UsersModel> datas = new List<UsersModel>();
Dt = _helper.GetAllUsers();
if (Dt.Rows.Count > 0)
{
foreach (DataRow dr in Dt.Rows)
{
UsersModel users = new UsersModel
{
UserID = Convert.ToInt32(dr["USERID"]),
UserName = dr["USERNAME"].ToString(),
Password = dr["PASSWORD"].ToString(),
SchoolCode = dr["SCHOOLCODE"].ToString(),
BranchCode = dr["MAINACCOUNTID"].ToString(),
IsActive = Convert.ToBoolean(dr["ISACTIVE"])
};
datas.Add(users);
}
}
else
{
ViewBag.ErrorMessage = "No Users Found";
}
return Json(new { data = datas }, JsonRequestBehavior.AllowGet) ;
}
Here is my jQuery Datatable being used in view GetAllUsers.cshtml
:
@model SiteAdministrator1._1._0.Models.UsersModel
@{
ViewBag.Title = "GetAllUsers";
Layout = "~/Views/Shared/_adminLayout.cshtml";
}
<h2>GetAllUsers</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table" id="usersList">
<thead>
<tr>
<th>
UserID
</th>
<th>
UserName
</th>
<th>
Password
</th>
<th>
SchoolCode
</th>
<th>
BranchCode
</th>
<th>
IsActive
</th>
</tr>
</thead>
<tbody></tbody>
</table>
@section scripts
{
<script>
$(document).ready(function () {
$('#usersList').Datatable({
"ajax": {
"url": "@Url.Action("GetAllUsers", "Admin")",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "UserID" },
{ "data": "UserName" },
{ "data": "Password" },
{ "data": "SchoolCode" },
{ "data": "BranchCode" },
{ "data": "IsActive" },
// Add other columns as per your model
]
});
});
</script>
Note:
- I have integrated all the jQuery and Datatable libraries.
- I have checked my Datatable connections, i.e. connection string) and queries written in the stored procedures
- I have used debugger to see if I am able to fetch the data from the databases and it works perfectly fine
- I am doing all this database fetching through ADO.NET (no entity data model, no Entity Framework)
- If I just fetch it in a list template bind my model it works fine and shows the data in ASP.NET MVC list template
2
Answers
this is a better approach as separating for rendering the view and fetching JSON data through different action methods is due to the way web page & client-server interactions function.
Can you try it this way too?