ASP.NET MVC 3 Ajax forms: Running JavaScript after DOM is updated
I have an MVC3 web project that includes very simple search form. It uses unobtrusive AJAX to bring back an HTML fragment containing the results in table form, and replaces an existing table. My problem is, I want to use the DataTables jQuery plug开发者_JS百科-in on the table to get sorting, paging, etc. But I cannot figure out the correct way to call the plug-in initialization code on the table.
What I have so far is this (this.Html.Script is just an extension method I wrote to auto-gen the script tags):
Search.cshtml:
@section ScriptSection
{
@this.Html.Script("libs/jquery.unobtrusive-ajax.min.js")
@this.Html.Script("libs/jquery.validate.js")
@this.Html.Script("libs/jquery.validate.unobtrusive.js")
@this.Html.Script("libs/jquery.dataTables.js")
<script type="text/javascript">
function initTable() {
$("table.datatable").dataTable();
}
</script>
}
@using ( this.Ajax.BeginForm("DoSearch", "Case", new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "results",
OnSuccess = "initTable"
}) )
{
<button type="submit" name="SearchType" value="date">Search</button>
}
<table id="results" class="datatable">
</table>
The problem is that initTable() appears to be called before the table I want is actually in the DOM. The outcome is that the results table is inserted into the page completely unstyled and with none of the dataTable features enabled.
Am I doing this right, or is there a different way to trigger the jQuery to run once the DOM has been updated?
put your code in:
$(document).ready(function() { // Handler for .ready() called. });
and see if that does it for you - the DOM should be completely loaded then.
Bleh, stupid mistake. jQuery DataTables needs the tags, which I wasn't using. Sorry for the noise.
精彩评论