The ASP.NET Core MVC controller encounters a null input parameter when called by an ajax request

Here is the scenario involving an ajax call:

...
$("#testBtn").click(function (e) {
    e.preventDefault();
    $.ajax({
        url: "/profile/GuestList",
        data: {"keytype": "1"},
        method: "POST",
        contentType: "application/json",
        success: function (data) {
           ...
        }
    });
});
...

This interacts with the following controller method:

[HttpPost]
public async Task<IActionResult> GuestList([FromBody]string keytype)
{
    try
    {
        return Ok();
    }
    catch (Exception ex)
    {

    }
}

The objective was initially to send an enum type, but that approach did not work. We then attempted to send an integer with a value of 1, only to receive 0 instead. Adding [FromBody] did not change this outcome. As a final attempt, we switched to sending a string and are now experiencing issues where the value received is null.

Where do you think the issue lies across all these variations?

Answer №1

Develop a new class

public class KeyTypeViewModel
{
    public string Keytype { get; set; }
}

Rectify the method by eliminating [FromBody]

[HttpPost]
public async Task<IActionResult> GuestList(KeyTypeViewModel viewModel)

Also, correct ajax functionality by removing contentType: "application/json"

$.ajax({
        url: "/profile/GuestList",
        data: {keytype: "1"},
        method: "POST",
       success: function (data) {
           ...
        }

Answer №2

Make sure to generate a Dto with the keytype attribute.

public class CustomDto
{
    public string Keytype { get; set; }
}

[HttpPost]
public async Task<IActionResult> UpdateGuestList([FromBody]CustomDto dto)

Answer №3

Make sure to convert your data to a string format in your Ajax call since you are passing it as a string input parameter for the POST method.

...
$("#testBtn").click(function (e) {
    e.preventDefault();
    $.ajax({
        url: "/profile/GuestList",
        data:  "1",
        method: "POST",
        contentType: "application/json",
        success: function (data) {
           ...
        }
    });
});
...

Answer №4

Make sure to convert your data into a string format before transmitting it.

Consider the following approach:

$.ajax({
   url: "/data/UserProfile",
   data: JSON.stringify({"user_id": "12345"}),
   method: "POST",
   contentType: "application/json",
   success: function (result) {
           ...
        }
    });

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

New Trainee - Error: document has not been defined

Encountering an Error message while attempting to run Intern tests from the test files directory. The structure of the directory is as follows: test resources rest pickup.js cashManagement.js gitignore intern.js packages.js ...

Optimal approach for managing numerous modals containing map data in Next.js

Hey there, I'm facing an issue while trying to utilize map data in conjunction with modals. Although I have set the state for all modals, when I use an array object within the map data, the modals end up showing duplicated. To provide clarity, let me ...

Using jQuery to dynamically swap out <tr> tags and all the elements inside of them

In order to enhance user experience, I am looking to automatically fill in certain form elements within a table when a link is clicked. The intention is for the fields to populate with predefined values and then convert into HTML paragraph elements, preven ...

Implementing a dynamic background change based on the current date in JavaScript

Is it possible to change the background of the body element based on the season using JavaScript? Here is a code snippet that demonstrates how to achieve this: // Function to determine the current season in the southern hemisphere // If no date is prov ...

In the Kendo AngularJS tree view, prevent the default behavior of allowing parent nodes to be checked

Hi there, I am currently using Kendo treeview with Angularjs. My tree view has checkboxes in a hierarchy as shown below Parent1 Child1 Child2 I would like the functionality to work as follows: Scenario 1: if a user selects Parent1 -> Child1, Chil ...

Tips for effectively overlaying one container on top of another in a responsive manner

There are a pair of containers. The main container functions as the parent, while the child container acts as a tag to categorize the content. The objective is to position the tag container at the top right corner of the main content container, slightly of ...

What is the best way to transfer information to a different NextJS page?

I want to implement a search input field. The idea is to allow the user to type something into the search bar and then send that input to another page where an API request will be made with the search content. Essentially, when the user types "something" ...

Creating smooth animations in JavaScript without relying on external libraries such as jQuery

Is there a way in JavaScript to make a <div> slide in from the right when hovered over, without relying on jQuery or other libraries? I'm looking for a modern browser-friendly solution. const div = document.querySelector('.fro ...

Display a preview on a separate page using ajax technology

I need assistance with previewing data entered into a large form in another tab before submitting it. I am currently using serialize() to pass the data through an AJAX URL and everything seems to be working fine until I try to display the data in another v ...

The information is being transmitted via an Ajax request, however, the PHP script is not able to

I am facing an issue with sending form data to a php script. Despite having what seems like correct Javascript and PHP code, the script is not receiving the data as expected. Before making the ajax request, the data appears to be in order. However, upon ...

No response being received from Ajax request

Having some trouble with an ajax function I developed for a small project. The issue lies in running the code inside the .done() function. This function is supposed to receive a json object from php (which I am obtaining a response via cURL), but it appear ...

What is the best way to retrieve AJAX response, specifically data, and store it in a PHP variable located beneath

Is there a way to store the data received from an AJAX response in a PHP variable located below this specific div? Essentially, I am looking for a method to access the AJAX response directly in PHP. <script> $(document).ready(function(){ ...

Retrieving objects based on a property that begins with any element from an array

I have a collection of contacts that I need to filter based on the country code. Specifically, I want to identify contacts whose phone numbers start with any of the selected country codes. var countries = ['1', '91', '55', &ap ...

Effective strategies for integrating Bootstrap and AngularJS without relying on jQuery

Currently exploring AngularJS after experimenting with Twitter's Bootstrap. I appreciate Bootstrap for its simplicity, sleek design, and mobile-friendliness. On the other hand, I have noticed a trend where people recommend using AngularJS over jQuery, ...

What is the most effective method for nesting loops in NodeJS and Mocha?

Currently, I am attempting to create a loop within a loop in my NodeJS code, but I seem to be getting lost along the way. The results are not as expected - sometimes callbacks are triggered twice and so on. My approach involves using the async module. I wo ...

Challenges with Scaling HTML5 Video onto Canvas

Attempting to extract a frame from an html5 video to generate a thumbnail, but encountering peculiar outcomes when the image is rendered onto canvas. The issue lies in the fact that the canvas displays only a greatly magnified portion of the video! Refer ...

Generate a new row for every value in a C# dropdown either before or after a Pipe character

I am facing a challenge with the custom attribute values for products in my database. To store these values, I save them as a character-separated list using the pipe symbol to separate each size. For instance, let's consider an Orange Dress with a cu ...

Issue with handling promise rejection of type error in node.js

Whenever I try running node server.js in Node.js, an error message pops up saying 'Cannot read property 'length' of undefined'. Despite installing all the necessary libraries (such as request) and browsing through various related posts ...

Use JavaScript to sift through an array and exclusively retrieve items that match a specific value

I am working with an array of objects that contain a phase key, and I want to filter out only the ones that have a specific phase value. Additionally, I need to map some other key/value pairs into the final return. Here is my current code: phaseToBlocks ( ...

What is the process for retrieving a jQuery AJAX response from a NodeJS endpoint?

After successfully initiating an ajax call to a set up endpoint, I sent a raw certificate as JSON and had the backend decode it. While I am able to display the decoded result using console.log, I am struggling to figure out how to return it as the final ou ...