What could be causing my AJAX request to send a null object to the server?

I'm currently working on an ajax request using XMLHttpRequest, but when the processRequest method is triggered, my MVC action gets hit and all object property values come up as null.

Ajax Class

import {Message} from "./Message";

export class AjaxHelper {

    private url: string;
    private data: Object;
    private callBackFunction: Function;

    constructor(url, data, callback) {
        this.url = url;
        this.data = data;
        this.callBackFunction = callback;
    }

    processRequest(): void {
        //var captcha = grecaptcha.getResponse();
        console.log("from ajax: " + this.data);
        const divOuterNotification = <HTMLDivElement>document.getElementById("divEmailMessage");

        var xhr = new XMLHttpRequest();
        xhr.open("POST", this.url, true);
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.onload = () => {
            if (xhr.status >= 200 && xhr.status <= 300) {
                this.callBackFunction(divOuterNotification, Message.enquirySent);
            } else {
                this.callBackFunction(divOuterNotification, Message.error);
            }
        }

        xhr.onerror = () => {
            this.callBackFunction(divOuterNotification, Message.error);
        }

        xhr.send(this.data);
    }

}

How to trigger the ajax request

var ajaxObj = new AjaxHelper("/Home/SendEmail", emailEnquiry, this.uiHelper.addNotification);
ajaxObj.processRequest();

MVC Action method

[HttpPost]
public IActionResult SendEmail(Enquiry emailEnquiry)
{
    return Json("worked");
}

Below, you can find the objects - the client object in JavaScript and its equivalent in C#.

JS Object

    var emailEnquiry = {
        SenderName: txtNameVal,
        SenderEmail: txtEmailVal,
        SenderTelephone: txtTelephoneVal,
        SenderEnquiry: txtEnquiryVal,
        CaptchaResponse: ""
    };

C# object

public class Enquiry
{
    [Required(AllowEmptyStrings = false)]
    public string SenderName { get; set; }
    [Required(AllowEmptyStrings = false)]
    public string SenderEmail { get; set; }
    public string SenderTelephone { get; set; }
    [Required(AllowEmptyStrings = false)]
    public string SenderEnquiry { get; set; }
    public string CaptchaResponse { get; set; }
}

Answer №1

Consider utilizing the FromBody attribute before your parameter declaration:

[HttpPost]
public IActionResult SubmitForm([FromBody] Form formDetails)
{
    return Json("success");
}

Answer №2

Experiment with the following method:

xhr.send(JSON.stringify(this.data));

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

Struggling to refine the result set using jsonpath-plus

Utilizing the jsonpath-plus module (typescript), I am currently working on navigating to a specific object within a json document. The target object is nested several levels deep, requiring passage through 2 levels of arrays. When using the following jsonp ...

Using *ngIf and *ngFor in Angular to switch between divs depending on their index values

Is there a way to toggle between two divs based on the index value using *ngIf in Angular? I have attempted to do so by toggling boolean values of true and false, but my current approach is not working. Here is what I have tried so far: <div *ngFor=&qu ...

Dealing with Sequelize Errors

After reviewing the code provided, I am curious if it would be sufficient to simply chain one .catch() onto the outermost sequelize task rather than attaching it to each individual task, which can create a cluttered appearance. Additionally, I am wonderin ...

Encountering a syntax error while transferring information from Ajax to PHP

I am currently experiencing an issue with my Ajax and PHP setup. Upon checking the browser console, I encountered the following error message: The following error occured: parsererror SyntaxError: Unexpected token <. Despite multiple attempts at debugg ...

Is it possible for consecutive json and jsonp requests to fail on Crossrider?

I am currently utilizing crossrider to develop a plugin that works across various browsers. Within my implementation, I have two consecutive AJAX requests (one JSON and one JSONP): The first request involves a JSON call for "login" which sets a brows ...

Optimal method for displaying the children component twice in Next.js

In order to create an infinite slider, I had to duplicate the data within my component. The data consists of an array containing a maximum of 20 items, each with an image. The slider is functioning perfectly. Although it may seem unconventional, it was n ...

Integrating JsonResult with Ajax forms and javascript: A comprehensive guide

When working with MVC4, how can I handle the response from a JsonResult action in an Ajax form? Most tutorials focus on handling html responses (ActionResult), making it difficult to find examples for Json results. I understand that this question is not ...

ng-required is ineffective when used with number inputs that have a minimum value requirement

In my form, I have implemented a checkbox that, when checked, toggles the visibility of a div using AngularJS's ng-show. Within this div, there is an input field of type "number" with a validation setting of min="10000". I am trying to prevent the f ...

Ways to align and fix a button within a specific div element

How can I make the button with position: fixed property only visible inside the second div and not remain fixed when scrolling to the first or last div? .one{ height:600px; width: 100%; background-color: re ...

When passing a function in Flask, it is important to note that the function will be rendered

In my project, there are flask functions named lock(id) and unlock() def lock(roomId): RoomTDG.update(roomId,True) def unlock(roomId): RoomTDG.update(roomId, False) I have integrated these functions into my template. To lock a specific room, I c ...

Reveal the administrator's details exclusively when the associated radio button is chosen

Managing administrators for a post can be done through an editing page with corresponding radio buttons. Each radio button is linked to a different administrator, and selecting one populates the form fields with that admin's details. The issue arises ...

Challenges with inferring return values in Typescript generics

I'm encountering an issue with TypeScript that I'm not sure if it's a bug or an unsupported feature. Here is a Minimal Viable Example (MVE) of the problem: interface ColumnOptions<R> { valueFormatter(params: R): string; valueGette ...

The generic parameter is extending a type but is being used in a contravariant position, causing TypeScript to struggle to unify it

When developing my functions, I aim to provide flexibility for consumers to use a wider type. However, I encounter issues when the type is used in a contravariant position and TypeScript raises complaints. Here is the simplified code snippet: function wra ...

Verify the presence and delete a table row from the JSON data that is returned

Is there a way to verify the presence of a label in the JSON response and exclude it from the displayed row in my table? In the code snippet below, you can observe that I am returning 'Page Name not defined'. I want to hide this label and any re ...

The reactivity of a Vue.js computed property diminishes when it is transmitted through an event handler

Within my main application, I've implemented a Modal component that receives content via an event whenever a modal needs to be displayed. The Modal content consists of a list with an associated action for each item, such as "select" or "remove": Vue. ...

Playing Sound Instantly in JavaScript without delay

I have successfully implemented playing sound with keys using HTML and .play. However, there is a delay as it waits for the track to finish playing before allowing me to play it again instantly upon each click. I am seeking a solution to trigger the sound ...

Is there a way to bypass TypeScript decorators and instead use NestJS entities like typical types?

I am trying to find a way to work with TypeScript entities in NestJS without using decorators. Currently, I define my entity like this: import { PrimaryGeneratedColumn, Column, Entity } from 'typeorm'; @Entity() export class User { @PrimaryGe ...

locate the presence of a specific letter within a sequence of characters

When dealing with strings like "Galley1", "Galley2", "Galley3", "Galley4", "Galley5", "Galley6" up to "Galley20", the task is to determine whether a condition is met. The condition should return true if the string contains a number between 1 and 7, inclusi ...

What is the best way to cycle through sprite positions within an array?

Having a string array containing the sprites to display: var lts = [ "letterA", "letterB", "letterC", "letterD", "letterE", "letterF" ]; These sprites are loaded in assets.js: function loadAssets(callback){ function loadSpri ...

Tips on organizing a JSON object for a JavaScript project

For my project, I am designing a data structure that utilizes JSON. My goal is to create an efficient method for searching and editing the JSON object. Which structure would be considered standard in this scenario? Is there a preferred way to implement eit ...