What is the best way to send a populated custom class from JavaScript to a .NET MVC app using AJAX?

I am working with a .NET class in C# called BusinessModel:

public class BusinessModel
{
    public string BlobName { get; set; }
    public string NewName { get; set; }
}

In my MVC Ajax Controller, I have an action called DoBusiness:

[HttpPost]
public ActionResult DoBusiness(string handle, BusinessModel businessData)
{
    // Implement business logic here.
}

Initially, I tried invoking this action using this JavaScript code:

var bd = JSON.stringify({ BlobName: "blob", NewName: "new" });

$.ajax({
    type: "POST",
    url: "/Ajax/DoBusiness",
    data: { handle: "MyHandle", businessData: bd },
    success: businessComplete,
    error: businessFailed
});

Upon inspecting the data sent via Fiddler, it was encoded as follows:

handle=MyHandle&businessData={"BlobName":"blob","NewName":"new"}

However, when checking the values passed to the controller action using Visual Studio debugger, the parameter "handle" had the expected value but "businessData" was null.

I then modified the JavaScript code to remove the JSON.stringify call:

var bd = { BlobName: "blob", NewName: "new" };

$.ajax({
    type: "POST",
    url: "/Ajax/DoBusiness",
    data: { handle: "MyHandle", businessData: bd },
    success: businessComplete,
    error: businessFailed
});

This time, the data sent via Fiddler was rendered differently:

handle=MyHandle&businessData%5BBlobName%5D=blob&businessData%5BNewName%5D=new

But even in this case, while "handle" was correct, both properties "BlobName" and "NewName" inside "businessData" were set to null in the controller action.

So the question remains: What mistake am I making? How can I properly populate the class in the controller action?

Additional note: This specific situation involves nested Ajax calls where complex objects are passed between them. While this example has been simplified, the core issue remains regarding object population within the controller action context.

Answer №1

Take a look at Stephan Muecke's response. His solution seems to be effective for the time being.

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 best way to run a promise once the endpoint has responded?

Is it possible to fulfill a promise after the response has been sent to the browser without using await? I must convert a video and save the output file in the operating system. For performance reasons, I want to avoid using await. Here's an example: ...

Error: The property 'children' is not found in type '{ children?: ReactNode; }'

I have been working on implementing the search bar feature from the provided link. Despite my efforts to match the types correctly, I keep encountering a TypeScript error. Homepage.tsx const [searchQuery, setSearchQuery] = useState(query || '' ...

JavaScript Discord bot encounters an issue: .sendMessage function is not recognized

Currently, I am developing a bot and testing its messaging functionality using .sendMessage method. (I prefer the bot not to send messages upon receiving any input, hence avoiding the use of: bot.on("message", function(message) {}); However, I am encoun ...

struggling with beginner-level JavaScript issues

Hey there, I've been running into a bit of an issue with my basic javascript skills: function tank(){ this.width = 50; this.length = 70; } function Person(job) { this.job = job; this.married = true; } var tank1 = tank(); console.log( ...

The maximum JSON length property limit was exceeded in the Ajax POST data in a JavaScript file

I'm encountering an issue when trying to send a large amount of data from a .js file to a .cs file through an ajax call. The error message I'm receiving is: "Error during serialization or deserialization using the JSON JavaScriptSerializer. The ...

Utilizing AJAX to Access a Json Web Service within ASP.NET

Any assistance would be highly valued. Here's the scenario: I am working on a .Net solution with 2 projects. One project hosts a web service while the other one calls this web service. The web service takes an integer ID as input and returns the form ...

Turning my dual button navigation into tabs to display distinct HTML pages beneath a designated header

body{ background:url(background.jpg); background-size: cover; } h1{ font-family: 'Dancing Script', cursive; font-size: 5em; color: white; text-align: center; margin-top: 25px; margin-bottom: 20px; } h2{ font-size: 18px; color: white; text-align ...

Is it possible to loop through a subset of a collection using *ngFor?

Is it possible to iterate through a specific range of elements in a collection using *ngFor? For instance, I have a group of checkboxes with their form control name and label specified as follows: [{id: 'c1', label: 'C1'}, ...] Assum ...

Tips for optimizing MongoDB query performance with larger datasets

When querying a MongoDB collection for data matching more than 10000 entries, even with an index in place, the query time exceeds 25 seconds. For instance, let's consider a table called People with fields name and age. I am trying to retrieve People ...

Ways to divide a route into a collection of Paths

I am working with a single path variable that looks like 'Customer\\Calls\\A1\\A2\\A3\\A4'. I need to split this path into an array with the following structure: 'Customer' 'Custom ...

I've encountered some issues with importing pagination from modules after installing SwiperJs

Having some issues with importing pagination from modules in SwiperJs for my nextjs project. The error message "Module not found: Package path ./modules is not exported from package" keeps popping up. I have tried updating the module to the latest version ...

Error message in Ionic 2: "Property is not found on type"

Currently, I am working on a project in Ionic 2 and have encountered a stumbling block with a seemingly simple task. My issue lies with a Textbox where I aim to input text that will then be displayed. I found some code on a website (http://www.tizag.com/j ...

Expanding your JavaScript skills: Tackling nested object key and value replacements

I am looking to manipulate the values of a nested object using JavaScript. The structure of the object is outlined below. let jsonObj = { "service":[ { "name":"restservice", "device&quo ...

Struggling to create a <td> with AngularJS directive

I am currently working on creating a directive for a large set of repeated HTML code that involves using tables and table data cells. Although I have experience creating directives for div elements in the past, this is my first attempt at incorporating the ...

What is the best way to implement asynchronous guarding for users?

Seeking assistance with implementing async route guard. I have a service that handles user authentication: @Injectable() export class GlobalVarsService { private isAgreeOk = new BehaviorSubject(false); constructor() { }; getAgreeState(): Obser ...

Invoking the callback function within the containing scope in Typescript

I am facing an issue with my Angular component where I have a class that includes common services and functions. While passing some functions as callbacks, the scope is getting lost during execution. Let me demonstrate the problem through the code below: @ ...

What steps should I take to craft an SQL command that retrieves the data, specifically an image, stored within a JSON

JSON Object {"images": ["https://unique-example.com/image.jpg"], "remarks": "completed", "documentList": [{"id": "GST", "value": "Goods and Services Tax"}]} sele ...

"Error encountered when attempting to call the requestFocus() method on a Java applet from JavaScript

I'm encountering an issue with calling the requestFocus() method in JavaScript. Uncaught TypeError: Object #<HTMLAppletElement> has no method 'requestFocus' Below is my JavaScript code within the <head> tags: function onLoad() ...

Having trouble importing a React component from a different directory?

I have included the folder structure for reference. Is there a way to successfully import the image component into the card component? No matter which path I try, I keep encountering this error: ./src/Components/Card/Card.js Module not found: Can't ...

Exploring the fundamentals of JavaScript within the context of Express.JS

Can you please explain the distinction between these two blocks of code in JavaScript? app.get("/api/products/1", (req, res) => { const singleProduct = products.find((product) => { product.id === 1; }); res.json(singleProduct); }) ...