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

AngularJS: Utilizing UI Bootstrap Popover with the Placement Set to 'bottom-right'

I am working with UI Bootstrap and AngularJS, attempting to customize a popover to have the 'bottom-right' placement instead of the default 'bottom' or 'right'. The desired functionality is illustrated in the image below. htt ...

Searching for a specific value in a JSON object using a variable in Python

json file 1 [{'one.10': 'eno', 'three': 1, 'two': False}, {'one.21': 'eon', 'three': 2, 'two': True}, {'one.31': 'noe', 'three': 3, 'two&apo ...

Encountered a problem while trying to retrieve JSON data from Cassandra DB using Java and sparkSession

I am currently working on a project that involves reading data from a Cassandra table using Java with sparkSession. The goal is to format the output as JSON. Here is the structure of my database: CREATE TABLE user ( user_id uuid, email ...

The JavaScript code appears to be missing or failing to execute on the website

Encountering a console error while trying to integrate jQuery into my website. The JavaScript file is throwing an error in the console that says: Uncaught ReferenceError: $ is not defined catergory.js:1 Even after following the suggested steps in this an ...

Hide elements forever once the form is submitted

I'm seeking help to figure out how to make certain elements disappear after a form submission on my website's dashboard page. Specifically, I need to hide three elements once the user has submitted a form. Elements that need to be hidden: .vc_t ...

Learn the process of dynamically updating the source of an HTML5 video

Currently, I am working on a project that involves dynamically loading multiple videos onto a webpage. The structure of my HTML is quite straightforward - it consists of a single video tag. <video controls preload width="520" height="350" id="video"> ...

Creating a session using jQuery to maintain user data without having to refresh the entire

Struggling with setting a session using jQuery and AJAX without the need for a page refresh. Currently, I can only set the session by pressing the refresh button, which is less than ideal. My PHP page is separate from my jQuery code, making it challengin ...

Tips for using the deferred method in ajax to enhance the efficiency of data loading from a php script

I recently discovered this method of fetching data simultaneously using ajax. However, I'm struggling to grasp the concept. Can someone please explain how to retrieve this data from a PHP script and then add it to a div similar to the example provided ...

Implementing custom CSS styles for HighCharts API pie chart drilldown labels

I successfully created a pie chart using highcharts and configured the chart with the following options: chart: { type: 'pie', }, In order to change the width of the text on the chart, I added the following options which force e ...

Incorporate a directive dynamically within a separate directive

Introducing the table-div directive, which is responsible for rendering both the header and body of a table. Each row within tbody has the option to incorporate additional functionality through a custom directive that can display data linked to its parent ...

Combine the entities within the object

I need to combine two objects that contain other objects within them, similar to the following structure: let selections = { 123: { abc: {name: 'abc'}, def: {name: 'def'} }, 456: { ghi: {name: ' ...

Implementing JSON and JQuery to dynamically update ActionLinks in an MVC table

Here's the HTML code I'm using to display image actions inside a table element: <%= Html.ActionLink("[EditImg]", "Edit", new { id = item.GrossBaseReconId }, new { id = "BaseReconEdit", rowsid = item.GrossBaseReconId }).Replace("[EditImg]", "& ...

"Retrieve a specific object from a JSON file using NextJS based on its ID

NextJs is the framework I am currently utilizing for my project. Is there a way to render a specific project based on its unique ID? { “projects”: [ { "id": 1, "picture": "portf.jpg" }, { ...

Issue with vue-cli3 eslint and compiler arising from conflicting vue/script-indent settings

Whenever my .eslint.js file includes this rule: "vue/script-indent": [ "error", 4, { "baseIndent": 1, "switchCase": 1, } ] and I save it, an error pops up: Error: Expected indentation of 32 spaces but only found 24 spaces ...

Changing letter cases in a textbox using Javascript

I have a challenge to create a code that can switch the case of text entered by the user. Here is what I currently have: var num; function toggleTextCase(str) { return str.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase( ...

BroccoliMergeTrees function encountered an unexpected data type while attempting to merge trees: TreeMerger (lint) was expecting a Broccoli node, but received an [object

Since switching to Ubuntu 18.04, I've been trying to set up my Ember development environment but have encountered an issue. While my ember project works fine on Windows, I'm getting the error "BroccoliMergeTrees (TreeMerger (lint)): Expected Broc ...

The Ajax functionality is not working properly following the switch in servers

My website uses a star rating ajax script, sourced from the following link. Recently, I switched my website hosting from a shared platform to a dedicated server that I manage with Plesk. Since the migration, the star rating script has ceased to function. ...

excessive memory usage in a simple react-native application

My experience with creating my first react native app has been more challenging than I initially expected. I'm having trouble understanding what I might be doing wrong. Initially, the app is simple, fetching data through Redux. componentWillMount() ...

Arranging an array of objects by a specific property in an Angular controller with the help of $filter

In my data set, there is an array of objects referred to as $scope.segments, which looks like this: [ { "_id": "55d1167655745c8d3679cdb5", "job_id": "55d0a6feab0332116d74b253", "status": "available", "sequence": 1, "body_original": " ...

Evaluation of Library (VueJS) - Displaying various components in an individual test case

Just starting out with testing and have a simple question: I am working on testing a checkbox component. I understand the basics, but how can I render multiple components within one it block? Here is my current code. I am stuck on the second test where I ...