Ron
Ron

Reputation: 1931

jquery Datatables and css not rendering in mvc 4

I have a simple view page, trying to render jquery datable for my view in MVC4.

My view [Admin.cshtml]

<div style="width:90%; margin:0 auto;">
    <table id="myTable">
        <thead>
            <tr>
                <th>Practice Name</th>
                <th>Practice Address</th>
                <th>Practice Email</th>
                <th>Practice Telephone</th>
                <th>Created Date</th>
            </tr>
        </thead>
    </table>
</div>

and my reference to css and js for jquery datatables are underneath the section:

 <link type="text/css" href="//cdn.datatables.net/1.10.9/css/jQuery.dataTables.min.css" rel="stylesheet"/> 
@section Scripts{
 <script type="text/javascript" src="//cdn.datatables.net/1.10.9/js/jQuery.dataTables.min.js"></script>
    <script>
        $(document).ready(function () {
            $('#myTable').dataTable({
                "ajax": {
                    "url": "/Home/Admin",
                    "type": "GET",
                    "datatype": "json"
                },
                "columns": [
                    { "data": "Practice_Name", "autowidth": true },
                    { "data": "Practice_Address", "autowidth": true },
                    { "data": "Practice_Email", "autowidth": true },
                    { "data": "Practice_Telephone", "autowidth": true },
                    { "data": "Created_Date", "autowidth": true }
                ]
            });
        });
    </script>
 }

and in my Controller, i have a simple GET section:

       public ActionResult Admin()
        {
            var data = db.Practices.ToList();
            return Json(new { data = data }, JsonRequestBehavior.AllowGet);
        }

But, when i run this application, i am getting my resultset like this

enter image description here

Where am i going wrong ?

Upvotes: 0

Views: 177

Answers (1)

Change your controller method name:

public ActionResult Admin() to public ActionResult GetAdminData()

Create another action method:

[Authorize] public ActionResult Admin () => View();

Modify your JavaScript code:

"url": "/Home/Admin" to "url": "/Home/GetAdminData"

And update CDN links because they are too old:

https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js

Why is all of this needed?

  1. When you navigate to /Home/Admin your return View (the Admin.cshtml)
  2. Your view contains some custom JavaScript logic which will try to fetch a list of items from the database (your GetAdminData method)
  3. GetAdminData returns JSON which can be used by DataTables in order to show your desired content on the page.

Upvotes: 2

Related Questions