Utilizing ASP.Net Core version 3 to effortlessly send a POST request to the controller

I am having difficulty with my POST request to an ASP.NET Core 3 server because the number always seems to be 0. Is there something specific in ASP.NET Core 3 that I might be missing?

Using the [FromBody] parameter has not resolved the issue. Even passing classes as parameters does not seem to change the values.

[HttpPost]
[Route("/api/add")]
public ActionResult<Dictionary<string, object>> Add(int number)
{

    // the value of 'number' is consistently 0 :(

    number += 1;

    var d = new Dictionary<string, object>
    {
        ["message"] = "Hello",
        ["number"] = number 
    };

    return Ok(d);
}
let input = { number: 5825 }

$.ajax(
    {
        url: `/api/add`,
        type: 'POST',
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(input),
        accepts: "application/json",
        complete: function (output) {
            // completed
        }
    }
);

My service configurations are as follows:

services.AddSession();
services.AddHttpContextAccessor();
services.AddControllersWithViews();

And the middleware I use includes:

app.UseSession();
app.UseStaticFiles();
app.UseRouting();
app.UseCors();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllerRoute("default", "{controller=Default}/{action=Index}/{id?}"); });

Answer №1

After reviewing the client code provided, it appears that the client is attempting to pass a complex type to a server expecting a simple type.

To resolve this issue, a new model must be created:

public class UserData {
    public int value { get; set; }
}

Next, bind the model to the designated action:

[HttpPost]
[Route("/api/sum")]
public IActionResult Sum([FromBody]UserData model) {

    if(ModelState.IsValid) {

        var value = model.value;
        value += 1;

        var result = new {
            message = "Greetings",
            total = value 
        };

        return Ok(result);
    }

    return BadRequest(ModelState);
}

Answer №2

When working with your JavaScript code, consider sending the number variable directly instead of the object input:

let number = 5825;

$.ajax(
    {
        url: `/api/add`,
        type: 'POST',
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: number,
        accepts: "application/json",
        complete: function (output) {
            // completed
        }
    }
);

Make use of the [FromBody] annotation in your controller:

[HttpPost]
[Route("/api/add")]
public ActionResult<Dictionary<string, object>> Add([FromBody]int number)
{

    // The issue might be that number is always 0 :(

    number += 1;

    var dictionary = new Dictionary<string, object>
    {
        ["message"] = "Hello",
        ["number"] = number 
    };

    return Ok(dictionary);
}

The problem could be because you are trying to send a complex type while the action only accepts a simple int type. Reach out if you need further assistance.

Answer №3

To implement @Nkosi's solution and add the property to the model, follow the steps below. Alternatively, if you prefer not to create a model, simply include the number in the URL query as shown:

let number = 5825;
    $.ajax(
        {
            url: '/api/add?number=' + number,
            type: 'POST',
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            accepts: "application/json",
            complete: function (output) {
                // completed
            }
        }
    );


[HttpPost]
[Route("/api/add")]

public ActionResult<Dictionary<string, object>> Add(int number)
{
  //...
}

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 correct method to choose an element in jQuery based on the function's id parameter

I'm having trouble deleting an item in my to-do list app. deleteToDoItem: function(id) { $(id).remove(); console.log(id); }, Here is the function that calls deleteToDoItem: function deleteItem(event) { var itemID, splitID, t ...

Bring JavaScript Function into Vue's index.html File

Recently in my code files, I noticed the following: function example() { console.log("testing"); } In another file, I have something like this: <head> <script src="../src/example.js" type="text/babel"></sc ...

Utilizing CSS files to incorporate loading icons in a component by dynamically updating based on passed props

Is it possible to store icons in CSS files and dynamically load them based on props passed into a component? In the provided example found at this CodeSandbox Link, SVG icons are loaded from the library named '@progress/kendo-svg-icons'. Instea ...

PHP: the images uploaded are not located within the designated folder

Having trouble uploading multiple images to a folder and saving them in the database? The images are not moving to the folder, even though the code works on localhost. Here is the code snippet: var abc = 0; // Declaring and defining global incremen ...

Tips on automating the process of moving overflowing elements into a dropdown menu

Challenge Description In need of a dynamic navigation bar, I faced the problem of displaying only the first X items on one line and have the remaining items hidden in a "Show more" dropdown. The challenge was to calculate the width of each item accurately ...

Buttons fail to function properly when inserted into Popover

I'm attempting to add 2 buttons to a popover triggered by the .clear-history button: <div class="modal-footer text-nowrap"> <button type="button" class="clear-history btn btn-link">Clear history</button> </div> const c ...

What is the process for incorporating a unique pop-up window in Shopify?

Hey there! I'm looking to incorporate a pop-up window that will appear when a user clicks on a link or button on the product page. This pop-up will display washing instructions, for example. I came across this code snippet, but it doesn't seem t ...

Ways to fix the loading error in AngularJS version 1.3.5?

My HTML page includes AngularJS components. Below is the code snippet: <!DOCTYPE html> <html ng-app="MyApp"> <head> <base href="/"> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> &l ...

Repeated information displayed in modal pop-ups

HTML <a class="btn" data-popup-open="popup-1" href="#">More Details</a> <div class="popup" data-popup="popup-1"> <div class="popup-inner"> <h2>Unbelievable! Check this Out! (Popup #1)</h2> ...

Unable to alter a global variable while iterating through an angular.forEach loop

I've encountered a challenge while attempting to modify a global variable within an Angular.forEach loop. Although I can successfully update the variable within the loop, I'm struggling to maintain those changes when accessing the variable outsi ...

Using AJAX to dynamically load content from a Wordpress website

Currently, I have been experimenting with an AJAX tutorial in an attempt to dynamically load my WordPress post content onto the homepage of my website without triggering a full page reload. However, for some reason, when clicking on the links, instead of ...

How can I make the lines of my drawer thicker in Material UI?

Currently, I'm in the process of implementing a left-side navigation bar for a web application I'm developing. The main challenge I'm facing is customizing the styles as desired when using the Drawer component. Specifically, I'm aiming ...

Identifying the class name of SVGAnimatedString

While working on creating an SVG map, I encountered an issue where the functions triggered by hovering over 'g' elements were not functioning as expected. In order to troubleshoot this problem, I decided to check for any issues with the class nam ...

Is there a way to upload a video, file, and PDF to a database using multer?

There is a database schema defined in the code below: const mongoose = require("mongoose"); const FormCourse_schema = new mongoose.Schema({ FormCourse: { type: mongoose.Schema.Types.ObjectId, ref: "cards", required: true, ...

Fade effect on content in Bootstrap carousel

I am currently making some updates to the website mcelroymotors.com. One issue I have encountered while working on the homepage carousel is that the caption only pops up on the first slide, and does not appear on any of the subsequent slides. I would lik ...

TestingCompilerFactory is not available as a provider

Currently troubleshooting my test file to identify the issue that is hindering a successful test run: import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { Component, Directive, Input, OnInit } from '@angula ...

The onmouseup event is not triggering in Vue.js 2

Show me the full code example here: https://github.com/kenpeter/test_vue_simple_audio_1 Attaching @onmouseup to the input range appears to have an issue. When I drag the slider, the function progressChange does not seem to be triggered. <input type ...

Ways to enable JavaScript code to accept input from both a text field and a text

I have a JavaScript code that allows users to input text and choose to make it bold, italicized, or underlined. For example, if the user checks the bold option, the text will appear in bold format. Here is the JavaScript code I am using: $('input[n ...

Is it possible to eliminate the blue border or focus rectangle from the item list of a Combobox DropDownList in a .Net WinForms application using C#?

I've created a custom ComboBox that looks like the one in this image (with a blue focus border): https://i.sstatic.net/HKnVS.png Here's the code: using CxFlatUI; using System; using System.ComponentModel; using System.Drawing; using System.Draw ...

Troubleshooting issues when integrating three.js GLTFLoader() with TypeScript due to conflicts with zimjs

Successfully loading a model using three.js GLTFLoader() with TypeScript in a nuxt.js application: this.mGLTFLoader = new (<any>THREE).GLTFLoader(); this.mGLTFLoader.load(pPath, (gltf) => this.onLoad(gltf), (xhr) => this.onProgress(xhr), (e) = ...