Casey Crookston Casey Crookston - 2 months ago 18
C# Question

Modal's partial view content does not refresh

I have a bootstrap modal which, when opened, hits the server to update the model with data that will be displayed to the screen. It works great the FIRST time the modal is opened, but after that, it always shows the same data as the first time it was opened.

In the view:

<div id="ChangeOrderModal" class="modal hide fade" style="width:1000px">
<div class="modal-body">
<div id="ChangeOrderTable"></div>
<div class="modal-footer">
<a href="#" data-dismiss="modal" class="btn">Close</a>

Script in the View to hit the server and update data:

var url = '@Url.Action("SetChangeOrderDate")';
$.post(url, { coDate: date, projId: @Model.Project.id_project }, function (data) {

That hits the action just fine, every time:

public ActionResult SetChangeOrderDate(string coDate, int projId)
return PartialView("_ChangeOrderTable", projectVM);

Then, in the partial view:

@foreach (var record in Model.ChangeOrder.Change_Order_Dash_List
... create table based on the list...

If I put a breakpoint right on that @foreach in the partial view, and get a count of the items, it is ALWAYS correct. Example: The first time the modal is opened, it has a count of 3. Then, three rows are rendered to the screen. I close the modal, open it by clicking on another icon, and this time the count is 7. I can even watch it loop over the HTML to render each row seven times.

But, the same three rows as last time appear on the screen.

What am I doing wrong?


You use of .replaceWith() means that in the first event, you replace the <div id="ChangeOrderTable"></div> element with the html your partial generates and that <div> element no longer exists.

In the 2nd event, your return the correct html, but $('#ChangeOrderTable').replaceWith(data); is no longer executed because there is no element with id="ChangeOrderTable" (so you just see the elements rendered in the first event).

Change the code for updating to DOM to use .html() which replaces the content of the element, not the element itself.

$.post(url, { coDate: date, projId: @Model.Project.id_project }, function (data) {

For further information, refer What's the difference between jQuery's replaceWith() and html()?