I've been learning how to successfully pass values to a Post method using AJAX in .NET Core 6 Razor Pages, but I am encountering some difficulties. Below are the relevant codes:
Front end:
function calculateSalary() {
var dropdown = document.getElementById("industryDropdown");
var selectedOption = dropdown.options[dropdown.selectedIndex];
var industryrange1, industryrange2;
industryrange1 = selectedOption.getAttribute('data-range1');
industryrange2 = selectedOption.getAttribute('data-range2');
var range1Value = String(industryrange1);
var range2Value = String(industryrange2);
console.log(range1Value);
console.log(range2Value);
try {
$.ajax({
type: 'POST',
headers: {RequestVerificationToken: $('input:hidden[name="__RequestVerificationToken"]').val()},
url: '/Index?handler=Calculate', // Replace with the actual path to your Razor Page method
contentType: 'application/json;charset=utf-8',
dataType: 'json',
data: JSON.stringify({ range1: range1Value, range2: range2Value }),
success: function (result) {
// Update the value of the textbox with the result
console.log(result);
$('#Message').val(result);
},
error: function (error) {
alert('Error:', error);
}
});
}
catch (error) {
console.error(error);
}
}
Upon clicking a button, this AJAX method passes 2 values to a function on the Model page. The Model function is as follows:
public IActionResult OnPostCalculate([FromBody] string range1, [FromBody] string range2)
{
var monthly_credit = employeeRepository.GetContribution(range1, range2);
foreach (var credit in monthly_credit)
{
Message = $"SSS Contribution = {credit}";
}
return new JsonResult(Message);
}
The goal is to pass the received values from AJAX to another function that retrieves data from an SQL table, puts the value in the "Message" variable, and displays that string in a textbox on the website.
The SQL function code is as follows:
public IEnumerable<SSS> GetContribution([FromBody] string range1, [FromBody] string range2)
{
double parsedRange1 = double.Parse(range1);
double parsedRange2 = double.Parse(range2);
//SQL code that returns values from tables
}
Issue and Attempted Solutions
I'm facing an issue where the parameters received by the model and SQL functions are null. Upon debugging, I discovered that:
- There are no JavaScript errors in the website console
- The data being sent via AJAX has values and is correct; console.log commands and the Network tab under Payload Request display them
- The null exception occurs in the SQL function, not the previous ones; somehow, the values of range1 and range2 in AJAX become null after being sent
I have tried running the code with and without [FromBody] and JSON.stringify, also adding [HttpPost] to the model function, yet the same error persists.
Any assistance on how to resolve this issue would be greatly appreciated.