Ways to transmit the appropriate model

Using AJAX, I am sending a model to the server via a POST request.

I have defined a model and a controller method for processing it.

 public class TestDto: BaseDto
{
    [Required]
    public ProductGalleryDto GalleryProduct { get; set; }

    public int? RetailPriceEur { get; set; }

    [Required]
    public int? AmountSpc { get; set; }

    public bool? PrizeSent { get; set; }

    public string Comment { get; set; }

    public DateTime? StartDate { get; set; }

    [Required]
    public DateTime? ExpirationDate { get; set; }

    public bool IsParticipant { get; internal set; }
}

public override IActionResult Post([FromBody] TestDto item)
        {
            if (!IsAdmin)
                return BadRequest(ApiErrorCodes.InsufficientPriveleges);

            if (!ModelState.IsValid)
                return BadRequest(ApiErrorCodes.RequiredFieldsMissing, ModelState.Keys.FirstOrDefault());
 }

JavaScript (JS):

var object = JSON.stringify({
        createddate: startdate,
        retailpriceeur: price,
        amountspc: spobicoinprice,
        prizesent: false,
        expirationdate: expirationdate,
        comment: comment,
        productgalleryid: productgalleryDto
    });

    $.ajax({
        headers: { "Authorization": "Bearer " + localStorage.getItem('authToken') },
        url: "/api/testapi/",
        method: "post",
        data: object,
        contentType: "application/json; charset=utf-8",
        success: function (result) {

        }
    });

The fields in JS must match those in the model. When the model is not valid, how can I fix this? Any assistance would be greatly appreciated.

Answer №1

It is important to send an object and not a JSON string in an ajax request, as shown in the following example:

 var animal = new Object();  
             animal.type = "dog";  
             animal.color = "brown";
             $.ajax({  
                 url: 'http://localhost:3413/api/animal',  
                 type: 'POST',   
                 data: animal,  
                 success: function (data, textStatus, xhr) {  
                     console.log(data);  
                 },  
                 error: function (xhr, textStatus, errorThrown) {  
                     console.log('Error in Operation');  
                 }  
             });  

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

How to populate an ExtJS 3.4 combobox with local JSON data in a few simple steps

I am utilizing ExtJS 3.4 and in need of populating a combobox with specific data obtained from a previous XMLHttpRequest, stored in a variable as follows: my_variable = "[{"cod_domini":"1","nom_domini":"Sant Esteve de Palautordera"},{"cod_domini":"2","no ...

Troubleshooting IE compatibility for $.trim() jQuery functionality

Having trouble with $.trim() not working in IE but works fine in Firefox. Any ideas why this might be happening? Thanks. $('#GuestEmailAddress').on('blur', function () { var $inputValue = $(this).val(); ...

Can anyone explain why I keep encountering an endless loop when using react hooks?

Having a bit of trouble with fetching data from a JS file that is mimicking an API with some endpoint methods. When I console log the data, everything seems fine, but for some reason, I keep running into an infinite loop when using hooks. I've tried t ...

How can I efficiently transfer a JavaScript array to a PHP script using the GET method?

My web application is designed with jQuery allowing users to manipulate visual elements. The next step is sending the JavaScript object state to PHP for storage in a database. While I prefer using GET, I am open to solutions that involve POST submission as ...

Adding elements into a PHP MySQL associative array using the array_push function

Trying to construct an associative array with PHP, utilizing an ajax script that accesses a JSON file. The script was successfully tested with the following PHP code: $testLocs = array( 'loc5' => array( 'info' => 'Some rand ...

Issue with jQuery's .height() method not updating

Here is the code I am working with: $(function() { $('#team-ch').click(function() { $('#team-camb-hert').height('auto'); }); }); I am trying to change the height of a div when a link is clicked. After adding an alert ...

Using jQuery JSONP only functions with URLs from the same site

I am looking to send a request to an API that returns data in json format. The API is located on a sub-domain of the domain where my script will be running (although currently it's on a completely different domain for development, localhost). My unde ...

Barely populated React application following setup

I have been diving into React for quite some time now. However, today when I attempted to start a new project, it generated an almost empty project. My usual command create-react-app 'name-of-my-app' was used. It ran for a while and completed th ...

React Alert: Please be advised that whitespace text nodes are not allowed as children of <tr> elements

Currently, I am encountering an error message regarding the spaces left in . Despite my efforts to search for a solution on Stack Overflow, I have been unable to find one because my project does not contain any or table elements due to it being built with ...

Experiencing problems with malfunctioning javascript tabs

As a beginner user and coder, I'm currently working on creating a portfolio website. I had the idea to implement tabs that would allow for content swapping, but unfortunately, I'm having trouble getting the JavaScript to function correctly. I at ...

React component failing to render even when event is triggered

For my latest project, I am creating a blog using react, next.js, and json-server. The blog is coming along nicely with dynamically loaded blog posts and UI elements. However, I've hit a roadblock when it comes to loading comments dynamically. The sp ...

Tips for handling a JSON payload retrieved through a POST request

I'm currently working on a button that triggers a POST call to retrieve a json response from the server. My goal is to display this json response in a new (chrome) browser tab. Here's what I have so far using Angular: $http.post(url, data) .t ...

Congratulations! Your product has been successfully added to Magento using Ajax

While using Firebug, I discovered that JSON generates a message within the success function. However, I am having trouble figuring out how to display it. As a workaround, I attempted to add the following code snippet: if(data.status == 'ERROR'){ ...

The AJAX request is failing to reach the server

I'm currently using AJAX to populate a dropdown, but for some reason the call isn't reaching the server. Upon checking Firebug, I see the following error: POST 0 status 404 not found This is the code I'm working with: function selec ...

Verifying user authorization for Microphone access prior to triggering event in React application

I have created a React component featuring a microphone button that operates as follows: OnMouseDown => Initiates audio recording by the user OnMouseUp => Ceases audio recording To elaborate, while the button is pressed down, the user can continue ...

Encountering a type error while executing ajax script in django

Currently, I am facing an issue with using jquery ajax to fetch json data on my webpage within the Django framework. Despite my efforts, I am unable to render the json data successfully. When attempting a simple console.log(data) as my initial step, nothin ...

The object tag does not function properly for video fallbacks when using the appendChild method

My video player application utilizes a modified version of video For everybody. The setup involves an HTML5 <video> tag encompassing an <object> tag for flash fallback on Internet Explorer. Everything functions smoothly when I employ this setup ...

Executing shell commands using an ajax call does not function properly on Linux systems

I have encountered an issue with my PHP script that utilizes shell_exec to execute a shell script. I am making an AJAX call to the PHP script. Interestingly, the script runs smoothly on Mac OS without any problems. However, when attempting to run it in my ...

Incorporating the non-typescript npm package "pondjs" into Meteor applications using typescript files

Implementing the Pondjs library into my project seemed straightforward at first: meteor npm install --save pondjs However, I'm encountering difficulties when trying to integrate it with my Typescript files. The documentation suggests: In order ...

Using jQuery Mobile for Enhanced PHP Form Submissions

My jquery mobile application code is not functioning properly when it comes to posting data from a form created using PHP. I even attempted using data-ajax="false", but the form still doesn't submit the data as expected. <table id="stock"> < ...