Currently struggling to retrieve data from an AJAX post request within a C# controller

I need assistance with sending data from JavaScript to a C# controller using AJAX. However, I am facing an issue where all the arguments in the Add method of my controller are showing up as null.

Below is my AJAX code:

function sendRequest(name, price, about){
    $.ajax({
        url: 'Services/Add',
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        data: {
            'name'  : name ,
            'price' : price,
            'about' : about,
        },
        dataType: "json",
        success: (response) => {
            if (response) {
                $('#result').fadeIn(200).html(response).fadeOut(200, () => {
                    location.reload()
                })
            }
        }
    })
}

This is my controller code:

[ApiController]
[Route("[controller]")]
public class ServicesController: Controller
{
    [HttpPost]
    [Route("Add")]
    public async Task Add(string? name, string? price, string? about)
    {
        await Context.Services.AddAsync(new Service
        {
            Name = name,
            Price = price,
            About = about
        });
        await Context.SaveChangesAsync();
    }
}

Answer №1

It seems like the controller binding is not functioning properly. When sending an object through ajax, but expecting three separate primitives, there might be an issue.

You can try the following approach:

    [HttpPost]
    [Route("Add")]
    public async Task Add(Service service)
    {
     await Context.Services.AddAsync(service);
    }

Alternatively, you could consider adding setup binding attributes

Answer №2

give this a shot

[HttpPost]
[Route("Create")]
public async Task CreateNewService(Service info) {
    //
}

Answer №3

Consider utilizing a service class to retrieve the JSON data instead of using individual values.

For more information, check out the following resources:

Answer №4

Using the $.post() function from the jQuery library has significantly improved my results in web development. Here's an example of how it can be used:

$.post(`Services/Update/?id=${id}&status=${status}`,
    function (response) {
        if (response) {
            $('#update').fadeIn(300).html(response).fadeOut(300, () => {
                location.reload();
            });
        }
    });

Ref: jQuery Documentation on $.post()

Answer №5

To determine whether your controller is authorized, check if it has the necessary permissions. If you wish for the controller to function without requiring authorization, make sure to include the allowanonymous attribute in your controller code, especially when no access token is provided in the ajax call.

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

Modifying SVG gradients with JavaScript

My goal is to modify the stop color of a gradient displayed in an SVG element. I've been trying to adjust the stop-color attribute, but so far, my attempts have not been successful: <svg><defs> <linearGradient gradientTransform="rotat ...

Automatically refreshing the page when the back button is clicked

Within my ASP.NET application, I have two pages - Page A and Page B. When a user clicks on a link on Page A, they are redirected to Page B. However, if the user then clicks the browser's back button while on Page B, I need to force a refresh of Page A ...

Converting JavaScript CanvasRenderingContext2D states array into a serialized format

Looking for a way to serialize a canvas' state in order to save it to a database for later restoration. Want to store the data as an object rather than a bitmap file. I've tried using .save() and .restore() on the context object, but they only m ...

passing data from the view to the controller

When I choose an option from the dropdown menu, the selected value is not being passed to the controller action method. Although the selected value is binding in Ajax, it is not binding in the controller action method. Check out our page <div class="ro ...

How can we reset multiple selected values (mui chips) in a React Material-UI Autocomplete field when changing the value in a different field?

Is there a way to clear the mui-chips in Material UI Autocomplete TextField when the value in another field is changed? I have been struggling with clearing the subtype value when the Type value changes. Although I can update the drop-down options based on ...

Is there a way for a Vue component to interact with a button or checkbox in order to dynamically update tooltip content and button style using a function?

Is it possible for a Vue component to trigger button clicks or checkbox checks in order to update tooltip text and button color using a function? Despite the presence of a handle() function in the code provided, these changes are not currently taking effec ...

Executing a JavaScript function within Python using Selenium: A beginner's guide

Within my JavaScript, there is a function called 'checkdata(code)' which requires an argument named 'code' to execute and returns a 15-character string. I recently discovered how to call functions without arguments in JavaScript. Howev ...

Tips for modifying AJAX behavior or restricting requests in Wicket

I am looking to prevent updates based on a specific JavaScript condition using AjaxSelfUpdatingTimerBehavior. WebMarkupContainer messagesWmc = new WebMarkupContainer( "messagesWmc" ) ; messagesWmc.setOutputMarkupId( true ) ; messagesWmc.add( ...

Error in Next.js: react-dom.development.js?ac89:14906 - Hook call is invalid. Hooks should only be used within a function component's body

Here is the code snippet I am working with: <div onClick={(e) => handleClick()}>Join Us</div> This is the handleClick function in my code: const handleClick = () => { console.log(Lang.getLocale()) }; And this is the Lang class metho ...

The Mongoose findOneAndUpdate method will only return the newly added document when using the $push

Provided here is a structured representation of my "profile" collection: { _id : ObjectId("2bb0fad110"), name : "Tommy", defaultrates : [ {_id : ObjectId("444cbcfd52"), rate : 35.0, raisedOn : "5/2/2009"}, {_ ...

Performing function in Vue.js when a change occurs

I recently started developing a Vue.js component that includes an input field for users to request a specific credit amount. My current goal is to create a function that will log the input amount to the console in real-time as it's being typed. Ultima ...

Retrieve data from Firestore using React and log it outside of the asynchronous function

Seeking a way to retrieve data from userRef and use it to initiate another asynchronous call to another document (e.g. bikes) in order to display that bikes doc on the page Currently, the userDetailslog in the Home screen function prints {"_U": ...

Tips for preventing the default action of a link created by JsHelper when making an Ajax request in cakePHP

Purpose: My objective is to trigger an ajax call by clicking a link and have the html content returned loaded into a specific div. I have created a link using JsHelper as shown below: <?php echo $this->Js->link('Perform ajax action!', ...

How can we detect line breaks within a selection using JavaScript?

Apologies for the lack of expertise in the content below, as it is being produced by a designer experimenting with coding :D The goal here is to determine the number of lines selected or highlighted by the cursor. When I mention "lines," I mean what is vi ...

Display a div element using AngularJS

Looking for a way to display a div using AngularJS, I came across some solutions on StackOverflow. However, implementing them did not work in my case. Here is my HTML code: <div id="myPanel" ng-controller="controllerDependance" ng-show="myvalue" clas ...

Guide to crafting a javascript variable from MySQL through the power of PHP and AJAX

I am not very experienced in working with AJAX and javascript. I am currently trying to pass longitude and latitude values from a MySQL database to javascript, but it doesn't seem to be working as expected. Can anyone help me figure out what I might b ...

React: An error has occurred - Properties cannot be read from an undefined value

THIS PROBLEM HAS BEEN RESOLVED. To see the solutions, scroll down or click here I've been working on a React project where I need to fetch JSON data from my server and render it using two functions. However, I'm encountering an issue where the v ...

The image will come to life with animation as the background position is adjusted using Skrollr

Trying to create a div that switches the background image every X pixels scrolled. Initially experimented with changing the background-image, including using sprites and adjusting background position, but encountered a distracting "flickering" effect. Exa ...

Autocomplete is failing to provide any results

I am experiencing an issue with the autocomplete script as it is not displaying any names under the input field. Below is the code snippet from my index file: <head> <html lang="en"> <meta charset="utf-8"> <meta na ...

Experience a magical Vue form wizard just like Wilio

Searching for a vuejs wizard form similar to the Wilio Wizard Form. Tried out the Binar Code Wizard Form, but it's not quite what I'm looking for. Need a form wizard with a simple progress bar and step numbers like Wilio. Is it possible to mod ...