简体   繁体   中英

jQuery Datatables plug-in not working with ASP.NET MVC

I am trying to add more functionality to a table in my MVC application by using the jquery datatables plug-in . I have added the following to my index.cshtml page to try and turn the table 'dailyreporttable' from a standard table into a datatable:

<script src="~/Scripts/DataTables-1.9.4/media/js/jquery.dataTables.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>

<script type="text/javascript">
    $(document).ready(function () {
        $('#dailyreporttable').dataTable();
    });
</script>

However when I preview the page in the browser, the datatables plus in has not been applied to the table, and it remains as a standard table. I don't have any experience with MVC or web development so I am not sure what exactly I am doing wrong.

You should be adding these references to your BundleConfig.cs file.

You will probably have a bundle being loaded in _Layout.cshtml:

@Scripts.Render("~/bundles/myBundle")

So add the jquery and datatables reference to that particular bundle, eg:

bundles.Add(new ScriptBundle("~/bundles/myBundle").Include(
     "~/Scripts/jquery-1.10.2.min.js"
     "~/Scripts/DataTab....ataTables.js"
));

You can check that the js files are being loaded by looking the the Firebug Net tab (if you're using Firefox)

Do you have a reference to the css file?? rel="stylesheet" type="text/css" href="../../media/css/jquery.dataTables.css"

try changing the order of script loading :

<script src="~/Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>
<script src="~/Scripts/DataTab....ataTables.js" type="text/javascript"></script>

Because datatables jquery based plugin and it requires jquery methods to run, so you have to include jQuery library first so that all the required methods gets available to the datatable plugin.

<head>
<script src="~/Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>
<script src="~/Scripts/DataTables-1.9.4/media/js/jquery.dataTables.js" type="text/javascript"></script>

<script type="text/javascript">
    $(document).ready(function () {
        $('#dailyreporttable').dataTable();
    });
</script>
</head>
<body>
<table id="dailyreporttable">
</table>
</body>

https://datatables.net/examples/basic_init/zero_configuration.html

$('#dailyreporttable').dataTable();

just move it out of the document.ready()

that seemed to do the trick for me,

another approach would be to use the ClientID

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM