user1490835 user1490835 - 3 months ago 124
jQuery Question

jquery datatable load in partial view dynamically with formatting in razor

I have a partial view which when first loads with the controller, loads the data in a jquery datatable as shown below. However once i run an event and call the partial action method, the data is still returned but the formatting is gone:
when full page loads
partialview return

Code to 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 call:

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 where the partial view is:

List of all appointments (including historical) for user



<div class="panel-body" id="partialViewAppointments">


@Html.Partial("ListAppointments", Model.Appointments)

</div>




Partial View:

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

Answer

You're replacing the HTML with the result from the server:

$("#partialViewAppointments").html(result2);

What's being sent from the server is just an HTML table, with no knowledge of jQuery DataTables or any other plugin. After the data is placed in the DOM, you would need to initialize that plugin again:

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