Send a complex Json object in a POST request

Hey guys, I'm new to the world of web development and I've encountered a challenging issue. I have a complex object with numerous fields filled by a JavaScript function that needs to be passed to a C# HttpPost Call.

I attempted to use JSON.Stringify to convert all the data into a string and then made an Ajax call to send it over to the C# script. However, when the call initiates, my input is consistently Null, leaving me confused about where the problem lies - during the ajax call or inside the HttpPost method.

If anyone could assist this n00b in distress, I would greatly appreciate it!

Ajax call:

$.ajax({
            type: "POST",  
            url: "/playlist",
            data: jsonPlaylist
        })

C# method:

public class JsonController : Controller
{


    [HttpPost]    
    [Route("playlist")]
    public Playlist getJson([FromBody]string playlist)
    {
        Playlist myPlaylist;
        if (playlist == null)
        {
            return null;
        }
        else
        {
            myPlaylist = JsonConvert.DeserializeObject<Playlist>(playlist);
            return myPlaylist;
        }
    }
}

Object Class:

 public class Playlist
{
    // Fields description here...
}

This is just a small snippet of the content being passed:

Sample json payload goes here...

}

Answer №1

If you want to bind the object directly in your model, you can use this approach:


public class JsonController : Controller
{


    [HttpPost]    
    [Route("playlist")]
    public Playlist getJson([FromBody]Playlist playlist)
    {
        if (playlist == null)
        {
            return null;
        }

    }
}

Remember to set the content type correctly when making AJAX calls:

$.ajax({
            type: "POST",  
            contentType: "application/json; charset=utf-8",
            url: "/playlist",
            data: jsonPlaylist
        })

Use a JSON structure like the one below:

 {
 "id": "playlist.m3u8",
"chunklists": [
    {
        "id": "chunklist-f1-v1-a1.m3u8",
        "times": [
            2.4299999931827188,
            0,
            0
        ],
        "chunks": [
            // More chunk data here
        ]
    },
    // More chunklist data here
],
"times": [
    3.5700000007636845,
    0,
    0
],
"serverId": "servername",
"clientIp": "ip",
"clientRegion": "region",
// More data properties here
}

Screenshots for reference:

Postman Screenshot

VS Visual Output

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

Determining whether both checks pass or if either one does

Hey there, I'm struggling with the following LINQ statement: var list=(from c in db.sales where c.id ==id && || c.name==name select new model { //..... }); The issue lies ...

Understanding the mechanism behind how the import statement knows to navigate to the package.json file

I find myself stuck in bed at the moment, and despite numerous Google searches with no clear answers, I have chosen to seek help here. Could someone please clarify how scoping works when using import in TypeScript and determining whether to check the pack ...

I am seeking a way to conceal text in an HTML document using JavaScript when the browser window width is less than a specified amount, and reveal it when the window width exceeds that value

I attempted to use the window.screen.width method, but it appears that the script only runs once (upon page load). I am seeking a way for the code to run continuously. Below is my JavaScript snippet: var textinSelected = document.getElementById("se ...

Adding a characteristic to every item in an array of objects

Currently, I am utilizing Node.js along with Mongoose to interact with a MongoDB database and retrieve an array of objects from a specific collection. However, my aim is to add an additional property to each of these retrieved objects. Below, you can see t ...

The Node.js promise failure can be unpredictable, despite being properly managed

In my journey to master MongoDB, I am currently exploring its capabilities by building a basic blog application. However, I have encountered an issue with the code responsible for saving blog posts - it seems to be inconsistent in its success rate, sometim ...

How to hide offcanvas navigation bar with one click in Bootstrap 5

There was an issue with a Bootstrap 5 project where the offcanvas menu would remain open after clicking on an anchor link. Is there a way to automatically close the offcanvas menu after clicking on an anchor link? <nav class="navbar fixed-top py ...

The unusual behavior of the :to attribute on @click in Vue

I have a specific element: Hashtag.vue: <template> <router-link :to="getTo" custom v-slot="{ navigate }"> <div role="link" @click="navigate"> {{text}}</div> </rout ...

Is it beneficial to vary the time between function calls when utilizing setInterval in JavaScript?

My website is displaying two words one letter at a time, with a 0.1s delay between letters and a 3s pause after each full word. I attempted using setTimeout, but it's not functioning as expected. What could be the issue in my code? var app = angular. ...

"Learn how to retrieve and assign a value to a select2 dropdown in Vue.js

Currently, I am utilizing vuejs to create and delete dynamic select elements, which is functioning properly. To view the working example, please click here: https://jsfiddle.net/nikleshraut/fgpdp700/2/ var vm = new Vue({ el: "#app", data: { opt ...

The error message "Access-Control-Allow-Origin header is missing on the requested resource" is still appearing despite having the correct CORS middleware set up

I am encountering the error message "No 'Access-Control-Allow-Origin' header is present on the requested resource" despite having implemented the necessary middleware in my express server. Here is the code snippet of the middleware placed before ...

Locate the Next Element Based on its Tag Name

CSS <div> <a href=''> Red </a> </div> <div> <div> <a href=''> Blue </a> </div> </div> <a href=''>Green</a> JavaScript $(document).ready(f ...

Display radio options when clicked upon

I am in the process of creating a set of radio buttons that will be utilized for capturing values to generate a subscription/modal checkout. My current situation involves having the radio button options visible. However, I aim to achieve a functionality wh ...

Is it possible to eliminate process.env.NODE_ENV using browserify/envify?

Currently, I am utilizing ReactJS through NPM and Browserify, but I am encountering difficulties while attempting to build it in production mode as mentioned in the readme. The code I have for setting up browserify is: var browserify = require('brows ...

Can you provide instructions on how to configure the npm settings to use the current directory in a pre

I'm currently working on setting the installation directory from where the user is installing to an npm config variable. This will help me reference it in my installation script. Can anyone advise if there is a command line solution for this or will ...

In order to set a condition for the mat date picker to display a text box in Angular if the selected date is for someone under 18 years old

I need assistance with displaying a text field based on age validation. The requirement is to show the input field only if the age is less than 18. Below is the code snippet I am currently working with: <form [formGroup]="form"> ...

As my character slides off the moving platform in this exciting Javascript canvas game, my heart

Can anyone help me figure out how to keep my player on the moving platform? I'm not sure if I need to add gravity or something else. I'm still learning the ropes. export function checkTopCollision({ item1, item2 }) { return ( item1.y + item ...

Parsing JSON lists in Android with dynamically named attributes

Looking to parse a JSON with the following structure: { "names": { "nameOne": { "item": "my item" }, "nameOther": { "item": "my item 2" }, ... more elements with unknown attribute names ...

How can an Express.js server detect when a browser has been closed or reloaded?

Currently tackling a project with an Express.js server. One query I have is how can this server detect when one of its users (browser) has been closed or reloaded? Any insights on this would be greatly appreciated! ...

Utilizing JQuery and AJAX to upload unprocessed data to a WebAPI

I need help figuring out how to send raw data to a webAPI using JQuery and Ajax. I've been struggling to make the data get transmitted successfully. The API endpoint functions correctly in Postman: https://i.sstatic.net/AX8zL.png Here is my simple J ...

If you scroll quickly, watch out for the flickering of the fadeIn and fadeOut

I have a script that fades in an element once the user scrolls more than 145px from the top of the page. $(window).scroll(function(){ if ($(this).scrollTop() > 145) { $('#fademenu').fadeIn(); } else { $('#fademenu').fadeOut(); } } ...