I am using ASP.NET Core 6. I have a razor view that has a section in it that is populated by an Ajax call:
<div id="assessmentTablesDiv">
<!-- ...content... -->
</div>
This <div>
is populated with the following call:
var assessmentTablesDiv = $('#assessmentTablesDiv');
var id = $('#adminDetailsAndOverviewId').val();
$.ajax({
url: "@Url.Action("LoadAssessmentTables", "Assessments")",
data: { id:id },
type: "GET",
success: function (data) {
assessmentTablesDiv.replaceWith(data);
}
});
The <div>
is replaced with a partial view that has a button that calls a modal form.
</div>
<div class="row">
<div class="col-md-12 mb-2 mt-2">
<button type="button" class="btn-sm btn-primary float-right"
data-toggle="ajax-modal" data-target="#mdAddAssessment"
data-url="@Url.Action("Create", "Assessments")"
title="Click add an assessment.">
Add Assessment
</button>
</div>
</div>
When I press the save button on the modal form, data is saved and the modal is closed. I then want to run the Ajax call to replace the data in assessmentTablesDiv
to show the newly saved data.
I have tried the following code, but it doesn't work:
$("#btnSave").on('click', function (event) {
if (validate()) {
var viewModel = {
"AssessmentId": $('#assessmentId').val(),
"AdmissionDetailsAndReviewsId": $('#adminDetailsAndReviewsId').val(),
"AssessmentTypeId": $('#AssessmentSelectionId').val(),
"DateMostRecent": $('#dateMostRecent').val(),
"IQSpecifyOrOther": $("#iqSpecifyOrOther").val(),
"Score": $('#score').val(),
}
$.ajax({
type: "POST",
url: "@Url.Action("SaveGeneralAssessment", "Assessments")",
headers: { "RequestVerificationToken": "@GetAntiXsrfRequestToken()" },
datatype: "json",
data: viewModel,
async: false,
success: function (response) {
$('#mdAddAssessment').modal('hide')
reloadAssessment();
},
failure: function (response) {
alert(JSON.stringify(response));
},
error: function (response) {
alert(JSON.stringify(response));
}
});
};
});
function reloadAssessment() {
var assessmentTablesDiv = $('#assessmentTablesDiv');
var id = $('#adminDetailsAndOverviewId').val();
$.ajax({
url: "@Url.Action("LoadAssessmentTables", "Assessments")",
data: { id: id },
type: "GET",
success: function (data) {
assessmentTablesDiv.replaceWith(data);
}
});
}
I don't want to reload the whole page as any other data entered on the page that hasn't been saved will be lost.
Any ideas?
Thanks
.html()
instead of .replaceWith():
this preserves the #assessmentTablesDiv
element without a chance of event-binding complications.
success: function (data) {
assessmentTablesDiv.html(data);
},
Handling Success and Failure Asynchronously Using .done()
and .fail()
.done(function (response) {
$('#mdAddAssessment').modal('hide');
reloadAssessment();
})
.fail(function (response) {
alert("An error occurred: " + JSON.stringify(response));
});
It should reload smooth, without reloading the page.