使用ajax重新加载后,jquery数据表格式化了

Baa*_*ali 3 asp.net-mvc jquery datatables

我有一个局部视图,当第一次加载控制器时,将数据加载到jquery数据表中,如下所示.但是,一旦我运行事件并调用部分操作方法,仍会返回数据,但格式化已消失: 当整页加载时 部分视图返回

返回partialView的代码:

public PartialViewResult ListAppointments(string _userId)
{
    var userId =  Convert.ToInt32(_userId);
    var o = (from s in db.tblAppointments.ToList()
             where s.UserId == userId
             select new AppointmentViewModel { AppointmentInstructorName = s.InstructorName, AppointmentLessonAddress = s.Address, LessonDateTime = s.LessonDate, UserId = s.UserId, Id = s.ID });

    return PartialView(o);
}
Run Code Online (Sandbox Code Playgroud)

jQuery调用:

function success(result) {
    var Id = $('#UserId').val();
    var data = JSON.stringify({"_userId": Id});
    $.ajax({
        type: "GET",
        url: "@Url.Action("ListAppointments", "Appointment")",
        data: data,
        success: function (result2) { $("#partialViewAppointments").html(result2); }
    });
}
Run Code Online (Sandbox Code Playgroud)

Razor的局部视图是:

<div class="panel-heading tabbable" tabindex="0"><h1>List of all appointments (including historical) for user</h1></div>
    <div class="panel-body" id="partialViewAppointments">
        @Html.Partial("ListAppointments", Model.Appointments)
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

局部视图:

 <table id="example" class="display" cellspacing="0" width="100%">
  <thead>
    <tr>
        <th>ID</th>
        <th>Instructor</th>
        <th>Lesson Date and Time</th>
        <th>Address (if different)</th>
        <th></th>

    </tr>
</thead>
<tfoot>
    <tr>
        <th>ID</th>
        <th>Instructor</th>
        <th>Lesson Date and Time</th>
        <th>Address (if different)</th>
        <th></th>

    </tr>
</tfoot>


<tbody>
    @if (Model != null)
    {
        foreach (var info in Model)
        {
            <tr>
                <td>@info.Id</td>
                <td>@info.AppointmentInstructorName</td>
                <td>@info.LessonDateTime</td>

                <td>@info.AppointmentLessonAddress</td>
                <td>@Html.ActionLink("Edit", "Edit", "Appointment", new { id = info.Id }, null)</td>
            </tr>

        }
    }

</tbody>

</table>
Run Code Online (Sandbox Code Playgroud)

Dav*_*vid 7

您正在使用服务器的结果替换HTML:

$("#partialViewAppointments").html(result2);
Run Code Online (Sandbox Code Playgroud)

从服务器发送的只是一个HTML table,不知道jQuery DataTables或任何其他插件.将数据放入DOM后,您需要再次初始化该插件:

$.ajax({
    type: "GET",
    url: "@Url.Action("ListAppointments", "Appointment")",
    data: data,
    success: function (result2) {
        $("#partialViewAppointments").html(result2);

        $('#example').DataTable(); // <-- right here
        // Using whatever options were used the first time, of course
    }
});
Run Code Online (Sandbox Code Playgroud)