The values of nested objects are not being passed as parameters from the AJAX call to the action method

How can I ensure that the nested object values in the parameter are passed correctly to the action method in the controller along with the full object?

When calling the AJAX method, the values in the object inside the red ring on the pictures do not get passed to the controller.

mapHub.client.requestForHelpInClient = function (requestDetails) {
                debugger;
                $.ajax({
                    type: "GET",
                    url: '@Url.Action("RequestPartialView", "Supplier")',
                    data: requestDetails,
                    success: function (response) {
                        $("#Request").html(response);
                    },
                    error: function (error) {
                        console.log(error);
                    }
                });                
            }

https://i.stack.imgur.com/1HCaP.png

function requestForHelp() {
            requestDetails = {
                CustomerId: @Model.Customer.CustomerID,
                NumberOfHours: $("#numberOfHoursTextBox").val(),
                TypeOfMachine: $("#typeOfMachineDropDownMenu").children("option:selected").val(),
                CustomerLocation: CustomerPosition,
                NearestSupplierList: nearestSuppliers
                //StartDate: $( "#startDate" ).val(),
                //EndDate: $( "#endDate" ).val(),
            }
            mapHub.server.requestForHelp(requestDetails);


public class RequestDetails
{
    public int CustomerId { get; set; }
    public Customer Customer { get; set; }
    public MapClient CustomerLocation { get; set; }
    public int NumberOfHours { get; set; }
    public string TypeOfMachine { get; set; }
    public List<MapClient> NearestSupplierList { get; set; }    
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
}

The signalr hub

public void RequestForHelp(RequestDetails requestDetails)
    {

        requestDetails.Customer =   Service.CustomerService.GetCustomerById(requestDetails.CustomerId);
Service.SupplierService.GetAspNetUserIDBySupplierID(requestDetails.NearestSupplierList[0].ClientId);

Clients.User(supplierAspNetUserID).requestForHelpInClient(requestDetails);
    }

Answer №1

Here are two important adjustments for you to make.

  1. The current method being used is GET, which does not support data transfer. Switch both the controller and ajax from GET to POST.

  2. Include a [FromBody] tag in the controller function. The data binder may require this, depending on your MVC version.

Controller:

[HttpPost]
public ActionResult RequestPartialView([FromBody]RequestDetails reqDetails)
{
   // code goes here 
}

Ajax:

mapHub.client.requestForHelpInClient = function (requestDetails) {
    $.ajax({
        type: "POST",
        url: '@Url.Action("RequestPartialView", "Supplier")',
        data: requestDetails,
        success: function (response) {
            $("#Request").html(response);
        },
        error: function (error) {
            console.log(error);
        }
    });  
}

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

JavaScript is having trouble locating the HTML select element

Having trouble selecting the HTML select element with JavaScript? You're not alone. Despite trying different solutions found online, like waiting for the window to fully load: window.onload = function(){ var opt = document.getElementsByName("prod ...

How to remove a specific type from a generic type in Typescript without using Exclude<>?

I am looking for a solution to prevent my function from working with Moment objects when storing values in local storage. Currently, the function dynamically stringifies and stores values, but I want to exclude Moment objects from being processed. Here is ...

ng-repeat to display items based on dropdown choice or user's search input

Utilizing $http to retrieve JSON data for display in a table. I have successfully implemented a search functionality where users can search the JSON data from an input field. Additionally, I now want to include a feature that allows users to filter the JSO ...

The erratic performance of the Click() function in Selenium

In my work on a Product automation project (Web CMS), I have encountered inconsistent behavior when using element.Click(). Our setup involves: Selenium + Nunit GUI(unit testing framework) - For running test cases locally on a specific environment Sele ...

jQuery parent() Function Explained

checkout this code snippet - https://jsfiddle.net/johndoe1994/xtu09zz9/ Let me explain the functionality of the code The code contains two containers: .first and .second. The .first container has two default divs with a class of .item. The .second contai ...

What is the process for bringing data from a REST API into a SQL Server database?

My REST API delivers a JSON-formatted response that looks like this: { "Employees" : [ { "userId":"romin", "jobTitleName":"Developer", "emailAddress":"<a href="/cdn-cgi/l/email-protection" class="__cf_ema ...

The Eclipse IDE is experiencing issues with the functionality of the JavaScript Number class

In my latest project, I decided to create a Dynamic Web Project using the Eclipse IDE 2019-12 along with Apache Tomcat 8.5.55 server. The main functionality of this project is that a user can input integers and receive their sum as an output. To ensure dat ...

Why is it that when accessing the property of an object within a computed object, it returns as undefined instead of the object itself? Which method would be more suitable in this

Salutations. To provide some context, my intention in posing this query is to dynamically render a child component within a form based on the selection made using the <app-selector> Vue component, as straightforward as that. To simplify matters, I ...

Utilizing NodeJS code and the SlackAPI to build a custom chatbot named PFBot

Recently, I came up with an idea for a Slack Bot that could censor inappropriate language used by users. For example, if a user types a curse word, the bot would automatically replace it with symbols based on the length of the word. Although I'm rela ...

Guide to mocking the 'git-simple' branchLocal function using jest.mock

Utilizing the simple-git package, I have implemented the following function: import simpleGit from 'simple-git'; /** * The function returns the ticket Id if present in the branch name * @returns ticket Id */ export const getTicketIdFromBranch ...

When submitting data through jQuery.ajax that includes the string "???", the value is transformed into "jQuery19107363727174233645_1373301489648?"

Server side script: var configuration = {"NumberOfCPUs":"2","NumberOfCores":"4","OSType":"Linux","OSVersion":"???"}; var identifier = 0; var responseReceived = false; //sending data to the server: $.ajax( { ...

Selecting an option from dropdown1 to retrieve a specific value from a JSON file

I currently have 2 dropdown lists to fill with data from a JSON file: $scope.categories = [ {name:"Blouse", sizes:["36","38","40","42","44","46","48","50"]}, {name:"Shirt", sizes:["36","38","40","42","44","46","48","50"]}, {name:"Pants", size ...

Is there a way to duplicate and insert a function in node.js if I only have its name?

I'm currently working on a code generation project and I've encountered a problem that I initially thought would be easy to solve. However, it seems to be more complicated than I anticipated. My task involves taking a method name as input, naviga ...

Having trouble displaying my klout score with ajax

I'm attempting to showcase a Klout score on a webpage Here's my code: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> var settings = { "url": "http://api.klout.co ...

Is the original image source revealed when clicked?

I've implemented an expand and collapse feature using jQuery/JavaScript. Clicking on the DIV causes the image inside to change state. However, clicking on the same DIV again doesn't return the image to its original state; it remains stuck in the ...

Struggling to remove a row from the MUI DataGrid within a MERN CRUD application with Redux/RTK?

Struggling to understand why the delete button isn't working on my Material UI (MUI V5) Data Grid table. As a beginner in coding, especially with MERN and Redux, my mind is overwhelmed after trying various solutions all weekend - Google, Stack Overflo ...

Setting the class attribute dynamically using code behind

Below is a snippet of code I am working with: div1.Attributes.Add("class", "displayNone"); It functions properly during page load but fails to do so during an OnClick event. The issue arises from the fact that my HTML element <div id="div1"></d ...

The entered value in the <input> field is not valid

I am encountering an issue where the input value is auto-filled, but when I click the submit button, the input field value is not recognized unless I modify something in it, such as deleting and adding the last word to the first name. Is there a way to m ...

What is the most effective method for accessing, editing, and outputting large JSON files in Node JS?

Task at hand: I need to handle large amounts of data (1 GB & more) in JSON format, perform formatting, parse the data, restructure the JSON, and return the newly formatted JSON as a response. What is the best approach for this situation? I read on a blog ...

Issue encountered while attempting to write KML objects to Google Earth API: NPObject error

Currently, I am working on a script that aims to extract data from Facebook and display it graphically on a Google Map using simple extruded polygons. The social integration and AJAX functionality are both working fine for me. However, whenever I try to ex ...