When sending multiple JSON objects in an HTTP POST request to an ASP.NET MVC controller action, they may not be properly bound

I am passing two JSON objects to an ASP.NET MVC controller action, but both parameters are showing as null.

Can anyone identify the error, possibly related to incorrect naming?

/* Source Unit */
var sourceParent = sourceNode.getParent();
var sourceUnitParentId = sourceParent == null ? null : sourceParent.data.key;
var sourceUnit = { unitId: sourceNode.data.key, parentId: sourceUnitParentId };
var sourceUnitJson = JSON.stringify(sourceUnit);

/* Target Unit */
var targetParent = targetNode.getParent();
var targetUnitParentId = targetParent == null ? null : targetParent.data.key;
var targetUnit = { unitId: targetNode.data.key, parentId: targetUnitParentId };
var targetUnitJson = JSON.stringify(targetUnit);

moveUnit(sourceUnitJson, targetUnitJson);



function moveUnit(sourceUnit, targetUnit) {
        $.ajax({
            url: '@Url.Action("Move", "Unit")',
            type: 'POST',
            data: { sourceUnit: sourceUnit, targetUnit: targetUnit },
            success: function (response) {

            },
            error: function (e) {

            }
        });
    }

[HttpPost]
        public ActionResult Move(DragDropUnitViewModel sourceUnit, DragDropUnitViewModel targetUnit)
        {
            Unit sUnit = Mapper.Map<DragDropUnitViewModel, Unit>(sourceUnit);
            Unit tUnit = Mapper.Map<DragDropUnitViewModel, Unit>(targetUnit);
            _unitService.MoveUnit(sUnit, tUnit);
            return new EmptyResult();
        }

Answer №1

Have you considered using a view model instead? When passing JSON to a controller action, it's recommended to define a view model with the necessary properties and then use JSON.stringify on the entire request.

Creating a view model:

public class MoveViewModel
{
    public DragDropUnitViewModel SourceUnit { get; set; }
    public DragDropUnitViewModel TargetUnit { get; set; }
}

Your controller action can now accept the view model as an argument:

[HttpPost]
public ActionResult Move(MoveViewModel model)
{
    Unit sUnit = Mapper.Map<DragDropUnitViewModel, Unit>(model.SourceUnit);
    Unit tUnit = Mapper.Map<DragDropUnitViewModel, Unit>(model.TargetUnit);
    _unitService.MoveUnit(sUnit, tUnit);
    return new EmptyResult();
}

To invoke this controller action using AJAX and send a JSON request, be sure to specify the correct content type:

/* Source Unit */
var sourceParent = sourceNode.getParent();
var sourceUnitParentId = sourceParent == null ? null : sourceParent.data.key;
var sourceUnit = { unitId: sourceNode.data.key, parentId: sourceUnitParentId };


/* Target Unit */
var targetParent = targetNode.getParent();
var targetUnitParentId = targetParent == null ? null : targetParent.data.key;
var targetUnit = { unitId: targetNode.data.key, parentId: targetUnitParentId };

/* build the view model */
var moveModel = { sourceUnit: sourceUnit, targetUnit: targetUnit };

/* Pass the view model to the server using an AJAX request */
moveUnit(moveModel);



function moveUnit(moveModel) {
    $.ajax({
        url: '@Url.Action("Move", "Unit")',
        type: 'POST',
        // Specify the correct content type for sending a JSON request
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(moveModel),
        success: function (response) {

        },
        error: function (e) {

        }
    });
}

Key points to remember:

  • If a controller action takes more than one argument, consider defining a view model.
  • If a controller action passes a domain model to a view, consider defining a view model.

In ASP.NET MVC, view models play a crucial role in maintaining clean architecture.

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

Different Ways to Access an Array in an EJS Template

After receiving a list of IDs from an API, I need to include them in a URL within an EJS template to retrieve the correct items. For example, the URL format is: Here are some example IDs: 526 876 929 The desired output inside the EJS template: <li&g ...

"Unlocking the Power of Pandas Dataframes: A Guide to Parsing MongoDB

I have a piece of code that exports JSON data from a MongoDB query like this: querywith open(r'/Month/Applications_test.json', 'w') as f: for x in dic: json.dump(x, f, default=json_util.default) The output JSON looks like this: ...

Access the specific scope I established in Angular console, excluding the entire scope

Is there a way to access only the $scope elements (variables and functions) created in my controller without getting everything ($$childTail, $$childHead, etc)? I know if I use: angular.element(document.querySelector('<selector-name>')).sc ...

jQuery's z-index feature is malfunctioning

When I hover over my menu, a box fades in. However, there is a small icon behind this box that I want to move to the front so it can be visible during hover. To see an example of my menu, click here: Navigation I attempted to address this by using jQuer ...

Test case does not treat similar content as similar

I've encountered an issue while working on a JsonExporter where the addition of JSON_PRETTY_PRINT has caused the testcase to fail unexpectedly. Even though there is no actual difference in the output, phpunit still detects a mismatch: // snippet from ...

Minimizing the size of a production application's bundle

In a production application I am working on, the bundle size is currently 8.06MB. # Output from npm build File sizes after gzip: 1.67 MB build/static/js/3.73cf59a2.chunk.js 794.29 KB build/typescript.worker.js 131.13 KB build/css.worker.js 1 ...

Remove the initial section of the text and provide the rest of the string

I am a beginner in the world of Javascript and unfortunately I have not been able to find an answer to my current problem. Here is the situation. On a webpage, I am receiving a URL that is sometimes presented in this format: http://url1.come/http://url2.c ...

Guide to creating a functional Async API

I am currently facing a challenge while developing an application for my institution. I need to allow users to access database information (currently using firebase) from an external server, so I set up a node.js server to facilitate communication and hand ...

Bootstrap Collapse function might not function properly immediately following the execution of Collapse Methods

Here is the reference link: http://jsfiddle.net/72nfxgjs/ The code snippet I used is from w3schools: http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_js_collapse&stacked=h <script type="text/javascript"> $("#collapse1").col ...

Safari IOS experiencing issue with element disappearing unexpectedly when input is focused

I am facing a situation similar to the one discussed in the question (iOS 8.3 fixed HTML element disappears on input focus), but my problem differs slightly. My chatbox iframe is embedded within a scrollable parent, and when the iframe is activated, it exp ...

Retrieving JSON Object within ajax success block

I'm facing some difficulty in retrieving my json object from an ajax call. In the handler, I am outputting the next id as follows: echo json_encode(array( "nextId" => 2 )); After that, I try to access it using data: $.ajax({ [...], dat ...

I am attempting to utilize the fetch API method to initialize the store's state, but for some reason, it is not functioning properly

Within my store.js file, I have a state called user_data, with its initial method set to fetch_user_data: export default new Vuex.Store({ state: { user_data: util.fetch_user_data('username') ... } located in the util.js file: util. ...

Exploring the distinctions between ajax, await, async, and

English is not my strong suit, so please bear with me if my writing seems odd. We have discovered two methods for transitioning from asynchronous ajax calls to synchronous ones. Using async: false Utilizing await Both achieve the same outcome, but I am ...

AngularJS - how to dynamically delete a directive from an element

Looking for a way to dynamically add or remove directives from compiled and linked elements? I have a page with numerous inputs and want to disable all of them if a specific flag is set. The conventional method using jQuery's element.prop('disabl ...

Is this AJAX request properly formatted?

I am attempting to send an array of variables to my CakePHP action for editing purposes. The array is created from the ids of table rows. Below is the javascript code snippet that can be found in my index.ctp file. <script type="text/javascript"> $( ...

I'm having trouble with my Selenium as it doesn't seem to be able to open

Hey there, I've been working on a script to login to Gmail, but I'm having trouble with entering the password after entering the email. public static void main(String[] args) throws Exception { System.setProperty("webdriver.chrome.driver", "E:&b ...

Adding information to a MySQL database table with Python

As a Python beginner, I am attempting to insert JSON file data into my database table using Python. However, despite not encountering any errors, I only receive the message: Tweet number 49634 is uploading to the server I'm struggling to identify wh ...

Develop a custom autocomplete feature using Formik in React for selecting values from an array of objects

Looking to Add Autocomplete Functionality in Your React Application Using Formik for Seamless Selection of Single and Multiple Values from an Array of Objects? Take a Look at this Code snippet! [see image below] (https://i.stack.imgur.com/ekkAi.png) arra ...

The JSON data may be improperly formatted

My script is not functioning correctly, it returns about 20 undefined values before finally displaying the full_name: function retrieveUserInfo(phrase) { $.ajax({ url: 'get_staff_details.aspx?rand=' + Math.random(), type: &ap ...

Guide to integrating react-phone-number-input into material-ui TextField

Would it be possible for me to use a Material UI TextField component as the inputComponent prop for the PhoneInput component from react-phone-number-input? I am facing an issue where I am unable to apply the ref successfully. Even though I can see the Mat ...