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

Sending an AJAX request to an external URL using PHP

I've been attempting to execute an ajax post request towards an external URL, and while the same request works fine in hurl.it, it doesn't seem to provide the expected output when I try it directly in the browser. When using hurl.it, I input the ...

What is the process for incorporating a new task into my HTML/CSS/JavaScript to-do list application when the Enter key is pressed?

Currently, I am working on developing a to-do list application using HTML, CSS, and JavaScript. The application includes a text input field for users to enter their tasks, along with an "Add Task" button. However, I want to enhance the user experience by a ...

Tips for utilizing a printer to print HTML content in PHP

I've stored HTML content in a variable as shown below: $message ="<div> <table align='center'> <tr><td><h1>Tipo de Documentos Report</h1></td></tr> <tr><td>< ...

When you scroll a fixed element on the page, the block is truncated

I made a modification for adding cart items and included a script for managing my cart The cart is supposed to stick to the right edge and scroll up and down on the page Everything seems to work, but there's a slight issue when I click on Add 1 and ...

Tips for avoiding template errors when retrieving data using Nuxt's fetch() method

After transitioning my vue app to a nuxt app, I encountered an issue with vue-slick-corousel. In the original vue app, everything worked smoothly with vue-slick-carousel, but after making the necessary modifications for nuxt, the carousel wouldn't dis ...

JavaScript heap running out of memory after upgrading from Angular 11 to versions 12, 13, or 14

I need assistance with resolving a JS heap out of memory issue that has been occurring when trying to start the local server ever since migrating from Angular 11 to Angular 12 (or 13 or 14, all versions tested with the same problem). This occurs during th ...

The implementation of pushing inside a foreach loop is not correctly adding elements to

I have encountered an issue with running a foreach loop and adding values to an array in my code. The first foreach loop works as expected, adding values properly to the array. However, the second foreach loop seems to be malfunctioning as none of its valu ...

JSON response is not being successfully passed in PHP Ajax form validation

I've been struggling to solve my code for the past few days but haven't had any success. I'm attempting to validate my login form using AJAX, however, it seems like there's an issue with my Jquery AJAX script. Every time I try, the con ...

The Nuxt.js and Vue.js Watchers are caught in an infinite loop caused by fluctuations in the values

Currently, I am working on a project using Nuxt.js/Vue.js for creating an application that can efficiently convert XML to JSON and vice versa. Users have the ability to input values into textareas, which are managed by CodeMirror. The textarea is connecte ...

Express - Unhandled promise rejection detected

I am working with two tables, one for graduates and another for mentors. My goal is to determine which table an email belongs to by using the provided endpoint. router.post("/reset/:email", async (req, res) => { //searching for the table from ...

What is the rationale behind using both useMemo and createSelector in this code?

This example from the React-Redux documentation showcases how a selector can be utilized in multiple component instances while depending on the component's props. import React, { useMemo } from 'react' import { useSelector } from 'reac ...

Retrieve a text and save it into a variable

Is there a way to extract a specific string and save it as a variable? For example, if I have the following URL: http://sub.site.com/WordsHere-t.jpg I am looking to extract just WordsHere. The length of this string can vary and will not always be 9 chara ...

UniData's Suite of Data Access Solutions for the .NET Framework

Currently, I am conducting research on accessing data in a UniData database from .NET code. My findings indicate that options such as UniObjects for .NET and U2.NET are available. Additionally, I came across this information, which seems to be related to ...

Tips for modifying a state array in Vuex

I have the ability to add and remove entries, but I'm struggling with editing. How can I achieve this using VUEJS, VUEX, and JavaScript? For adding entries, I know I should use PUSH, and for removing entries, SPLICE works fine. But what about editing ...

Employing on() for triggering a form submission

I am attempting to attach a submit event handler to a form that may not always be present in the DOM, so I am using .on(): $('body').on("form","submit", function(e){}) However, when checking Firebug, it shows: $("body").on is not a function ...

Eliminate inner margin from the canvas of a bar chart created with ChartJS

I am looking to use Chart.js to create a single stacked bar chart that visualizes progress towards a specific financial goal. I have added a dotted line on top of the chart to represent this goal amount. The issue I am facing is that there is unwanted pad ...

Attempting to assign the object retrieved from the interface as the new value for window.location.href

I encountered an issue where the error message Type MyInterface' is not assignable to type 'string' popped up. Although I comprehend the problem, finding a suitable solution has proven to be challenging. MyInterface solely returns one item, ...

Numerous points of interaction within ion-item

Within my ion-list, each ion-item contains a link to navigate to the next page. When tapping on an ion-item, it successfully navigates to the detail page. The problem arises when there is a button inside each ion-item that triggers an action. Tapping on t ...

Conceal the Submit button upon completing the form submission using the load method

When creating a form and sending a request to another page, I use the following code: $(document).ready(function() { $("#send").click(function() { var text = $("#text").val(); var email = $("#email").val(); $("#exp").load("sendmail.php",{text: ...