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

What is the best way to assign multiple controllers to a single view in angularJS?

My Attempt: $routeProvider .when('/paintings', { controller: 'imageController' , 'getPaintingImages' templateUrl: 'paintings.html' }) .when('/foods', ...

Vue allows a child component to share a method with its parent component

Which approach do you believe is more effective among the options below? [ 1 ] Opting to utilize $emit for exposing methods from child components to parent components $emit('updateAPI', exposeAPI({ childMethod: this.childMethod })) OR [ 2 ] ...

Encountering an issue with Angular 1.6 and webpack: controller registration problem

Currently developing a small application with Angular for the frontend, and my frontend module is structured as follows: https://i.stack.imgur.com/tjfPB.png In the app.js file, the main Angular module 'weatherApp' is defined: angular.module(&a ...

Using Selenium Webdriver with C# to dynamically expand a RadMenu Webelement in Javascript

I am currently working with Selenium WebDriver in C# and facing an issue with a RadMenu. My goal is to hover over the menu so that it expands a sub menu, where I can find a specific webelement to click. I have tried using JavaScript for this purpose, but u ...

Removing a portion of an item with the power of RxJS

I possess the subsequent entity: const myObject = { items:[ { name: 'John', age: 35, children: [ { child: 'Eric', age: 10, sex: 'M' }, { ...

Could you explain the functionality of this compact C# code?

Recently, I joined a new team that specializes in automating processes using C# and Selenium. However, there is one line of code that I can't seem to understand: driver.FindElement(Elements.OkLink).click() While I grasp the purpose of driver and ...

What is the correct way to update the state of an object in ReactJS using Redux?

Hello, I am facing an issue with storing input field values in the state object named 'userInfo'. Here is what my code looks like: <TextField onChange={this.handleUserUsername.bind(this)} value={this.props.userInfo.username} /> ...

How can you use AJAX and jQuery to animate one container and fade in another when $_GET['var'] is set and new content is loaded?

There is a <table id="pickups"> located in the file /pages/home.php. By default, the file index.php includes home.php if no other page is specified. When you click on an element (logfile) in a specific column of the table, the container with the clas ...

Scroll positioning determines the height of an entity

Here's a code snippet I'm working with: HTML: <div id="wrap"> <div id="column"></div> </div> CSS: #wrap { display: block; height: 2000px; width: 400px } #column { display: block; height: 20px; ...

Providing a callback function along with the specific execution context for it to be executed

myFn is a function that executes an asynchronous task and triggers the callback upon successful completion. SearchController.prototype.show = function (query) { this.searchService.myFn(arg1, this.myCallback); //I want to preserve the reference of `th ...

Tips for retrieving the Solana unix_timestamp on the front-end using JavaScript

Solana Rust smart contracts have access to solana_program::clock::Clock::get()?.unix_timestamp which is seconds from epoch (midnight Jan 1st 1970 GMT) but has a significant drift from any real-world time-zone as a result of Solana's processing delays ...

How can I access the ng-template in a component?

How can I reference <ng-template #modal_Template> in my component.ts file? Previously, I triggered a modal using a button on my HTML file and included this code: <button type="button" class="btn btn-primary" (click)="openModal(modal_Template)"> ...

Error updating model: The `teams` model cannot be modified once it has been compiled

After spending hours researching on StackOverflow, I came across numerous articles related to my issue. However, I am still unable to identify what mistake I have made here. Here is my code: models/Team.js const mongoose = require('mongoose'); ...

The current version of HTML5 Context Menus is now available

I'm in need of implementing the HTML5 Context Menu feature. Currently, only Firefox supports it. My main objective is to add some menu options without replacing the existing context menu. How can I achieve the same functionality now? I am aware of va ...

NG-show does not function properly with Angular validation messages when there are two input fields present

I have created a form with two modes: 'Create' and 'Edit'. Depending on the mode selected, specific div content is displayed in different areas of the layout. The content of the div includes an input field and validation messages relate ...

One singular ASMX web method invocation

I have a web method on an asmx page that I am calling using jQuery Ajax. Everything works fine the first time, but subsequent calls to the web method are not successful. [WebMethod(EnableSession = true)] public static string WsCom(AjaxObjectsHelper.UpdateP ...

Learn the process of effortlessly transferring user information to a MongoDB database

Using socket.io, I am broadcasting geolocation data (lat, lng) and updating the marker icon on a map every time a user connects to the app. When a user from Japan connects, their position is shared with me and vice versa. The issue arises when I only want ...

Is there a way for me to monitor the ngSrc attribute of an image element and retrieve the updated width and height within my personalized directive?

Here is a snippet from index.html: <img ng-src="{{ImageURL}}" my-image/> This is from app.js: var app = angular.module('plunker', []); app.controller('MyCtl', function($scope) { $scope.ImageURL = ""; $scope.ImgWidth = 0; ...

Unable to retrieve JEnumerable<JToken> child elements

When trying to call the code below in its current state, I am getting ,"Name":"Newtonsoft.Json.Linq.JEnumerable`1[Newtonsoft.Json.Linq.JToken]" as a result. If I modify the relevant line to var property = myObject[propertyNames.Last()].FirstOrDefault(); ...

What is the reason for the find() method not displaying the most recent data from a MongoDB database in an Express.js application?

Upon calling the app.post('/form-submit', funtion(req, res)) method, my expectation is for it to first save the data using save(). This works fine, but then when I call the find() method, it shows all the data from the mongoDB database except for ...