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

时间:2016-08-15 13:34:03

标签: jquery asp.net-mvc datatables

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

返回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);
}

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); }
    });
}

部分视图的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>

部分视图:

 <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>

1 个答案:

答案 0 :(得分:1)

您正在替换容器中的整个DOM,而不是使用DataTable API来更新它的数据存储。

您有两种选择:

1 - 强力解决方案,重新初始化DT:

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).Datatable(); }
        });
    }

选项2 - 了解围绕aaData的API(DataTable内部数据存储)。您可以通过row().data() api https://datatables.net/reference/api/row().data()

每行迭代执行此操作

或者 - 了解Datatable中的aaData存储 http://legacy.datatables.net/usage/server-side - 请注意这是legacy api文档,但它在某种程度上仍然相关