The ASP.NET Core 2.1.1 controller encounters null data upon receiving an AJAX post request

Struggling with sending a JavaScript value from my razor page to a controller in ASP.NET. The value always ends up being null, despite reaching the controller breakpoint. I've searched for solutions without much success.

I'm not very familiar with JavaScript, so any tips or guidance would be greatly appreciated. Here's the snippet of JavaScript causing the issue:

 var clickButton = function (buttonId) {
        $.ajax({
            type: "POST",
            async: false,
            cache: false,
            crossDomain: false,
            contentType: "application/json; charset=utf-8",
            url: "v1/buttons",
            dataType: "json",
            data: '{ buttonId:'+JSON.stringify( "buttonId" ) + '}',
            success: function (result) {
                //console.log("clickButton OK => " + result);
            }, 
            timeout: 500
        }); 
    }

Here is the corresponding C# controller code:

[Route( "v1/[controller]" )]
public class ButtonsController : Controller
{
 ...
  [HttpPost]
  public IActionResult OnButtonClicked( string buttonId )
  {
    // buttonId = null !!!
   ...

Additionally, encountering issues passing a boolean value to another controller where it defaults to false. Could this be related to a security restriction preventing unauthorized users from sending data via POST?

Answer №1

The issue resided in the JSON structure, and I managed to extract the value by making a minor adjustment, even though it was well concealed.

 var clickButton = function (buttonNo) {
     console.log("clicked: " + buttonNo);
     $.ajax({
         type: "POST",
         url: "v1/buttons/",
         dataType: "json",
         data: { "buttonId": buttonNo }, // < === this is where the problem lay !!
         success: function (result) {
         }, 
      }); 
    }

I have updated the controller to accept a string for identifying the button. Here's how it looks now:

[Route( "v1/[controller]" )]
public class ButtonsController : Controller
{
  ...
  [HttpPost]
  public IActionResult PostButtonClick( string buttonId ) {
    // The buttonId variable now holds a value !!!
  }
} 

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

Locating an image within another image using Node.js

I possess 2 bmp visuals. ImageA depicts a screenshot (illustration) while ImageB represents a subset of it - such as an icon. I am seeking to pinpoint the precise X,Y coordinates of ImageB within ImageA (provided that it is present). Do you have any su ...

What exactly is the significance of this line: Loaded += MyWindow_Loaded;

Coming from a background in VB.NET, I am currently working on learning the syntax of C#. ...

Having difficulty assigning properties in react-redux

I'm experiencing an issue with my code that involves using both React and Redux. The problem lies in the fact that this.props.comments is coming up as undefined. Can anyone identify what may be amiss? reducer.js: import {Map,List} from 'immutab ...

The issue of receiving a 500 error when making a POST request in node.js

I have created my own unique REST API that utilizes an NLP API internally. I need to post data on their URL, but unfortunately I am encountering an error that is causing my API to return a 500 error to the frontend. Below is a snippet of my server.js code ...

Checking that an object's keys are all present in an array in TypeScript should be a top priority

I am working with a const object that is used to simulate enums. My goal is to extract the keys from this object and store them in an array. I want TypeScript to generate an error if any of these keys are missing from the array. // Enum definition. export ...

Exploring ways to modify the orientation of the Table of Contents in Aspose.Word for C# .Net

When using Aspose.Word to create a table of contents, I encountered an issue. My document is currently set to right-to-left direction, but I need to change it to rtl (right-to-left). ...

Error encountered while attempting to save a Mongoose post on Heroku, although it is successful

My aim is to post to my MongoDB Atlas database using node, express, mongoose, and Heroku. While a Postman POST request with Raw JSON body: { "title": "heroku post", "description": "post me plsssss" } works f ...

Update user control attribute based on a calendar event

Within the code snippet provided, the method calling the property change is SetCaloriesBurnedStats(selectedDate), and everything else appears to be functioning correctly. An example of a simple user control is as follows: public string BigText { get; set ...

Using native DLLs in ASP.NET: A step-by-step guide

Question: I am currently using System.Data.OracleClient, which requires OracleInstantClient and native dll's for functionality. Unfortunately, due to restrictions on my company laptop, I do not have administrator rights to install or manipulate files ...

Exploring the compatibility of Next.js with jest for utilizing third-party ESM npm packages

Caught between the proverbial rock and a hard place. My app was built using: t3-stack: v6.2.1 - T3 stack Next.js: v12.3.1 jest: v29.3.1 Followed Next.js documentation for setting up jest with Rust Compiler at https://nextjs.org/docs/testing#setting-up-j ...

Distinguishing Data Input Formats for REST WCF Services (JSON vs XML)

So, I am experimenting with WCF and creating a restful service. Currently, users are sending me data through http post requests in json format and I have one method set up to receive this data. But now I want to configure another method to be able to acce ...

Unable to locate template or render function for Vue Draggable Next component

Looking to incorporate Vue Draggable Next into a Vue 3 example page but encountering some challenges. I've attempted to follow the instructions in the repository. However, I ran into issues when importing the Vue Draggable Next component and had to re ...

When the OnSubmit function is called, it triggers three other functions and then verifies the return types. However, one of the functions is failing to be

Creating a form that collects user input, and upon submission triggers the check_three_func() function <form method="post" action="register_action.php" id="register_form" name="register_form" onsubmit="return check_three_func()"> <br> &l ...

The jQuery code functions smoothly on computers, but experiences delays when running on an iPhone

I was working on my website and trying to add a div that sticks to the top of the browser when it scrolls out of view. I found a script that works well on desktop, but when testing it on iPhone, there is a slight delay before the div pops back up in the ri ...

Having trouble passing data from JavaScript to PHP with AJAX

I attempted to use AJAX to send data from an array (emp) and other string variables like 'gtotal' in my code, but the data did not transfer to the PHP file. Despite no errors being shown, when I removed the isset() function it displayed an error ...

Is a single f.select impacting another f.select in the same form? (undesired)

I am facing an issue where adding a new HTML element like: <%= f.date_select :date, { id: "date-select"} %> is impacting my existing collection select: <%= f.collection_select :id, Customer.where(business_id: current_c ...

P/Invoke - performing basic arithmetic operations with structured parameters

Check out my C code: real_T addition(const struct_T parameters) { return parameters.a + parameters.b; } typedef struct { real_T a; real_T b; } struct_T; typedef double real_T; This is how I call it from my C# code: using System.Runtime.Int ...

What is the best way to refresh VUE components while executing a promise?

Seeking assistance with updating the DOM to display a loading element while a login screen is submitted and stopping it when errors occur. Struggling to figure out how to update the DOM when the promise resolves using Vue.js, Vuex, and Vuetify. Setting a ...

What sets apart returning Task<bool> from simply returning bool?

Hopefully this is a straightforward and helpful explanation. I am working with C# MVC Web API in ASP.NET Core 1. I am developing web methods and have come across examples of handling data retrieval. For instance, here's an example: public async Tas ...

Bringing in JavaScript files from a Bootstrap theme to incorporate them into a Vue3 application

Incorporating Bootstrap 5, a HTML theme with a CSS bundle file, and separate JS bundle files (main JS bundle file and plugin bundle file) containing Bootstrap code base + custom template features into a Vue 3 project is my current objective. I aim to utili ...