How can we fix the null parameters being received by the ModelPage function?

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.

Answer №1

Make changes to the ajax code below:

$.ajax({
            type: 'POST',
            beforeSend: function (xhr) {
                xhr.setRequestHeader("XSRF-TOKEN",
                    $('input:hidden[name="__RequestVerificationToken"]').val());
                   },
            url: '/Index?handler=Calculate', // Ensure this path matches your Razor Page method
           
            data: { range1: range1Value, range2: range2Value },
       
            success: function (result) {
                // Update the textbox value with the result
                console.log(result);
                $('#Message').val(result);
            },
            error: function (error) {
                alert('An Error Occurred:', error);
            }
        });

Next:

[HttpPost]
public IActionResult OnPostCalculate( string range1,  string range2)
{
...}

In program.cs:

builder.Services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");

Remember to include in the view:

@Html.AntiForgeryToken()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Decomposing a Vue.js API response into multiple variables

Utilizing vue to send http requests and store data in variables can be done like so: the api response will have the following structure: data: data: [id:1... etc] function: fetchOffers() { this.$http.get('http://127.0.0.1:8000/api/of ...

Is there a way to resize SVG images without having to modify the underlying source code?

Within my Vue Single File Component, there is a prop labeled svg, which holds a string of SVG markup like <svg>...</svg>. What is the best way to render and resize this SVG content? ...

Simulating a mobile device screen size using an embedded iframe

Imagine this scenario: What if instead of adjusting the browser window size to showcase a responsive web design, we could load the site into an IFRAME with the dimensions of a mobile screen. Could this concept actually work? Picture having an IFRAME like ...

Access the child component within an @ChildComponent directive in Angular

Is it possible to retrieve child components of another component? For instance, consider the following QueryList: @ContentChildren(SysColumn) syscolumns: QueryList<SysColumn>; This QueryList will contain all instances of the SysColumns class, which ...

Ways to extract individual values from a Json Array and utilize them individually

I have a JSON data structure that I need to parse and separate each field into different arrays, so that I can use them individually. For instance, I want to split my data into two rooms: room 1 and room 2. After separating the data, I need to format it a ...

Using Vue.js to update content in input files

I have a Vue.js template file that includes data containing various documents. Within the page, there is a table with rows that feature upload file input buttons, structured like this: <tr v-for="(doc, index) in documents"> <td :id="'doc-& ...

Enhanced jQuery Embed Code validation for user input using a textarea

Currently, I am developing a website that allows users to input embed codes from popular platforms such as Twitter, YouTube, Instagram, Facebook, and so on. The embed code undergoes validation checks and is saved if it meets the criteria. However, when us ...

Which method is better for presenting data: PHP or JavaScript?

Currently, I am diving into vue.js on laracasts.com where Jeffrey Way demonstrates 2 ways to showcase data on a webpage. One method involves displaying data using Laravel foreach loops, while the other utilizes vue.js. This has led me to ponder: is there ...

In NextJS 12, an UnhandledPromiseRejectionWarning occurs when trying to reference the TextEncoder which is not defined

Currently, I am working on developing a Spotify clone using NextJS 12 along with a Tailwind CSS template. To initiate the project, I executed the following command: npx create-next-app -e with-tailwindcss spotify-2. The project was successfully created, b ...

Move on to the next iteration in the FOR loop in Node JS

Is there a way to skip item 3 in the loop without breaking it? for (var i = 1; i<= 9; i++) { if (i==3) break; console.log(i); } I had a tough time searching for an answer online because I am unsure of the exact terminology to use. Desired output: ...

Integrate an item into the request body utilizing the $.load() function in jQuery

Currently, I am using a POST request via jQuery's $.load function to retrieve data to display in a window. This is what I am currently doing: var testObject = { thing1: 'data1', thing2: 'data2', thing3: &a ...

Could someone provide some clarification on this callback related to node.js?

With the abundance of node.js tutorials available showing how to create a server, it can be overwhelming as they are all coded in different ways. The question then arises - when should you write it one way versus another? Unfortunately, none of the tutoria ...

The Javascript executor in Selenium is delivering a null value

My JavaScript code is causing some issues when executed with Selenium's JavascriptExecutor. Strangely, the code returns null through Selenium but a value in Firefox developer console. function temp(){ var attribute = jQuery(jQuery("[name='q& ...

What are the benefits of keeping JavaScript and HTML separate in web development?

Recently, I came across the concept of Unobtrusive JavaScript while researching best practices in the realm of JavaScript. One particular point that grabbed my attention was the idea of separating functionality (the "behavior layer") from a web page's ...

Setting up webpack encore for async and await in a Symfony 4 and VueJs project

After setting up a VueJs project within Symfony 4, I encountered an unexpected error involving await and async (Uncaught ReferenceError: regeneratorRuntime is not defined) I've come across plenty of resources for webpack, but nothing specifically for ...

Is there a straightforward method to retrieve all information from Vue.js?

Is there a way to extract all of this data? I've attempted using this._data.forEach but it doesn't seem to be effective. Thank you! data() { return { childData: '', credit: '', company: '', email: ...

Can you please explain how to switch the focused slide by clicking on a specific slide in swiper.js?

When using swiper in centeredSlides mode with the loop option set to true, I want a clicked slide to become the centered slide in the swiper carousel. Swiper provides me with the index of the clicked slide, but how can I use it to change the centered slide ...

JavaScript animation for sequencing traffic lights

I have been working on completing a task that was assigned to me. (iii) Explain the organization of an array that could manage the traffic light sequence. (iv) Develop a script that utilizes the array outlined in part (iii) to create an animated display ...

Perform the action only when the record is fresh

Currently in my ASP.NET/C# project, I have implemented an AJAX Timer for periodic data retrieval from the backend. The code snippet I am using within the Timer Tick event handler looks something like this: Here is my code: OdbcDataReader dr = cmd.Execute ...

"Changing a Java script base addon file to a customized addon in Odoo 16: A step-by-step guide

Here is the JavaScript file located in the "documents" enterprise base addon: I want to include the field "document_type_id" in the export const inspectorFields = [] array through a custom addon. /** @odoo-module **/ import { device } from "web.confi ...