简体   繁体   中英

ASP.NET MVC partial view jquery datatables

I have a problem with jQuery Datatables plugin in mvc.

I have a view with ajax-form whitch load a partial view with table on sumbit.

View

...
    @using (Ajax.BeginForm("MyAction", "MyController", new AjaxOptions { UpdateTargetId = "myList" }, new { @id = "searchForm", @class = "form-horizontal" }))
    {
                                // some html  
    }
    <div id="myList">

    </div>

Partial View with table

@model IEnumerable<Item>
<table id="productsTable">
    <thead>
    <tr>
        <th>Name</th>
        <th>Description</th>
        <th></th>
    </tr>
    </thead>
    <tbody>
    @foreach (var item in Model)
    {
        <tr>
            <td>@Html.DisplayFor(x => item.Name)</td>
            <td>@Html.DisplayFor(x => item.Description)</td>
            <td>
                <div>
                    <a href="@Url.Action("Edit", "MyController", new {id =            item.Id})">
                    </a>
                    <a href="@Url.Action("Delete", "MyController", new {id = item.Id})" >
                    </a>
                </div>
            </td>
        </tr>
    }
    </tbody>
</table>

The problem is that if I put script

$(document).ready(function() {
   $('#productsTable').DataTable();
});

in main View it will be not work because partial view load by ajax. And if I put this script in partial view it will be work with delay: at first user will see simple html table and than it will be convert to datatable.

Is there any way to correct load partial view with datatable? Thanks for advices.

You can't do anything on the server to "preload" the datatable, since it can only be run on the client. To run DataTable() , the browser needs to have loaded both jQuery and HTML before you can transform it, which is why there is a "blink" of ugly.

I suggest you load it (with Ajax if you wish) into a div with CSS position:absolute; and visibility:hidden; (not display:none; and position it somewhere off screen (for example with left: -3000em; or similar). After everything is loaded and DataTable() has run, you can move the div to where it should be with JS and toggle position and visibility back to normal.

You can even do this with a sweet fade-in effect, if you want. :)

$(document).ready(function() {
   $('#productsTable').DataTable();
});

you should place this code inside the success of ajax call. I think this may solve your problem :)

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