Currently, I have a functioning project built on a booking system in asp.net core that integrates a google Timeline chart. The interactive element involves a modal popup, which displays a partial view for data input when the chart is clicked. Utilizing Javascript, a click event on the save button triggers the sending of data to the controller for validation. Subsequently, the validated data is returned to Javascript, where it is displayed in the modal popup. However, an issue arises when I implement the [ValidateAntiForgeryToken]
attribute on the controller.
The relevant code sections are outlined as follows:
StartUp:
services.AddAntiforgery(options => {
options.HeaderName = "RequestVerificationToken";
});
Javascript:
(function() {
var PlaceHolderElement = $('#PlaceHolderHere');
PlaceHolderElement.on('click', '[data-save="modal"]', function(event) {
event.preventDefault();
var form = $(this).parents('.modal').find('form');
var token = $("input[name='__RequestVerificationToken']").val();
var actionUrl = form.attr('action');
var sendData = form.serialize();
$.ajax({
type: 'POST',
url: actionUrl,
data: sendData,
}).done(function(data1) {
var newBody = $('.modal-body', data1);
PlaceHolderElement.find('.modal-body').replaceWith(newBody);
var isValid = newBody.find('[name="IsValid"]').val() === 'True';
var isValid2 = newBody.find('[name="BookingFree"]').val() === 'True';
if (isValid && isValid2) {
PlaceHolderElement.find('.modal').modal('hide');
location.reload();
}
})
})
Controller:
[HttpPost]
public IActionResult EditBooking(BookingViewModel model) {
if (ModelState.IsValid) {
... other code
}
}
Introducing the [ValidateAntiForgeryToken] attribute to the controller requires a modification in the Javascript section:
data: {
model: sendData,
__RequestVerificationToken: token,
}
However, this adjustment leads to the model being empty upon validation. Using a string declaration for the model results in receiving a string output instead. Additionally, attempting to send the token in the headers fails the token validation process. The ultimate goal is to have the data properly stored in the model for the ModelState to reflect its validity.