Encountering issues with multiple arguments in ajax within a C# MVC application - Further details included

There seems to be a missing piece in my code. Here's my controller method

public void SubmitSweep(int personID, int DD, int MM, int YYYY, int hh, int mm, int dealId)

Here's how I define my button

<button id="submit@(person.Id)" class="btn btn-secondary" OnClick="submitSweep(@(person.Id), @(person.sweepDay), @(person.sweepMonth), @(person.sweepYear), @(person.sweepHour), @(person.sweepMinutes), @(person.dealId))">Submit Sweep</button>

And here's my JS function

function submitSweep(thePersonID, sweepDay, sweepMonth, sweepYear, sweepHours, sweepMinutes, theDealId) {
        
        $.ajax({
            type: 'POST',
            url: '@Url.Action("SubmitSweep", "Home")',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: JSON.stringify({ personID: thePersonID, DD: sweepDay, MM: sweepMonth, YYYY: sweepYear, hh: sweepHours, mm: sweepMinutes, dealId: theDealId }),
            success: function (data) {
                alert("Success");
            },
            error: function (ob, errStr) {
                alert("An error occured.Please try after sometime." + errStr + " " + ob.responseText);
            }
        });
    }

The function is being executed and the arguments are being populated. However, after some investigation, I believe the issue lies within the AJAX data field. If I remove all arguments from the controller, the breakpoint is reached, leading me to believe the error is in the data line.

If I modify my JS function as follows

function submitSweep(thePersonID, sweepDay, sweepMonth, sweepYear, sweepHours, sweepMinutes, theDealId) {
        
        var obj = {};
        obj.personID = thePersonID;
        obj.DD = sweepDay;
        obj.MM = sweepMonth;
        obj.YYYY = sweepYear;
        obj.hh = sweepHours;
        obj.mm = sweepMinutes
        obj.dealId = theDealId;

        $.ajax({
            type: 'POST',
            url: '@Url.Action("SubmitSweep", "Home")',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: obj, 
            success: function (data) {
                alert("Success");
            },
            error: function (ob, errStr) {
                alert("An error occured.Please try after sometime." + errStr + " " + ob.responseText);
            }
        });
    }

I receive an error with the title tag reading Invalid JSON primitive: personID. It's worth noting that I pass the obj in the Data element.

If I change the data line to

data: JSON.stringify(obj),

I then get an error message with the title indicating that an item with the same key has already been added. In both of these scenarios, my controller breakpoint is never reached.

I'm using Visual Studio 2022, so my libraries are mostly up-to-date.

Any assistance or guidance would be greatly appreciated.

Cheers

J

Answer №1

When working with JSON, it's necessary to retrieve data from the body. Only one input parameter can be obtained from the body in an action. This is where a view model comes in handy:

public class ViewModel
{
public int personID {get; set;}
public int DD {get; set;}
public int MM {get; set;} 
public int YYYY {get; set;}
public int hh {get; set;}
public int mm {get; set;}
public int dealId {get; set;}
}

Then in the action:

public ActionResult SubmitSweep([FromBody] ViewModel model)
{

}

Alternatively, if you prefer to keep the action unchanged, you'll need to remove contentType: json from your AJAX call and avoid stringifying the object:

$.ajax({
            type: 'POST',
            url: '@Url.Action("SubmitSweep", "Home")',
            dataType: "json",
            data: obj, 
           ...

Answer №2

After finally solving the issue, I wanted to share my solution in case it helps someone else facing the same frustrating problem!

The root of the problem lay in my controller method signature. I made a crucial change from what was originally stated in the question to:

public void SubmitSweep(int personID, int day, int month, int year, int hour, int minute, int dealId)

In addition, I updated the parameter names in my JS function to align with this modification:

function submitSweep(thePersonID, sweepDay, sweepMonth, sweepYear, sweepHours, sweepMinutes, theDealId) {
        
        var obj = {};
        obj.personID = thePersonID;
        obj.day = sweepDay;
        obj.month = sweepMonth;
        obj.year = sweepYear;
        obj.hour = sweepHours;
        obj.minute = sweepMinutes;
        obj.dealId = theDealId;

        $.ajax({
            type: 'POST',
            url: '@Url.Action("SubmitSweep", "Home")',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: JSON.stringify(obj), 
            success: function (data) {
                alert("Success");
            },
            error: function (ob, errStr) {
                alert("An error occured.Please try after sometime." + errStr + " " + ob.responseText);
            }
        });
    }

With these adjustments, everything now functions as intended. This experience reminded me that both JavaScript and C# are case-sensitive, whereas the posted URL is not. Hopefully, this solution will prevent others from making the same mistake. Lesson learned: always opt for meaningful variable names!

J

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

When an AJAX call is made during a PHP session that has timed out

I am working on an AJAX form that handles data authentication. In the event of a session timeout, I need to implement a redirect to the login page. How can I go about achieving this? Here is an excerpt from my simplified server-side code: function doExecu ...

Create a function that binds a select dropdown to each table column header using JavaScript Object Notation (JSON), and then populate an HTML table with the

I have a dynamic table populated with JSON data, and I would like to add a select dropdown for each column. The challenge is that the number of columns is not fixed and they are also populated by JSON. Therefore, I want the select dropdown at the top of ea ...

Is there a way to use Ajax to analyze and contrast information from two separate web links?

I am looking to compare and display the genre_ids from the first link and the id from the second link. Example: genre_ids: [ 18, 878, ] { id: 18, name: "Drama", }, { id: 878, name: "Science Fiction", } Result: Drama, Science Fiction $(document).ready( ...

Issue with arrow functions in Reactjs Material-UI - Unexpected token error

I am currently trying to integrate components from material-ui into a project based on react-rocket-boilerplate. An error message is appearing: [23:55:11] gulp-notify: [Compile Error] C:/react-rocket-boilerplate/app/js/components/Sidebar.js: Unexpected ...

When it comes to JavaScript, the evaluation order of arguments and delayed evaluation play a crucial

Assuming function( arg1, arg2 ), is it true that arg1 will always evaluate before arg2 (unlike traditional C)? Is there a way to create a function where arguments are not evaluated immediately, but only on demand? For instance, in if( cond1 || cond2 ), c ...

"Enhancing functionality with ajax buttons in Ruby on Rails

I'm facing an issue with this specific button: controller class ProductsController < ApplicationController def test @product = Product.find(params[:my][:id]) @k = params[:my][:k] @product.update_attribute :amount, @product.amount + @k.to_i resp ...

Proper method for incorporating loading and error messages with the help of useContext and react hooks

Currently, I have a context.js file that makes an ajax call and stores the data in an array to be shared across components. While adding some 'loading ...' text during the loading process using axios, I feel there might be a better way to handle ...

Why can't JQuery/javascript's dynamic gallery's images be used as buttons instead of links?

I've been struggling with my online portfolio for several nights as I build my website. Despite exhaustive internet searches, I couldn't quite articulate my problem in words and tried multiple workarounds. To see the issue, please visit the beta ...

What is the best way to refresh a navigation bar after making an API request, such as when using Google Sign-In?

Struggling to grasp the hook concept in this particular scenario: The flow goes like this - the user logs in with Google, which updates the session state. Consequently, the visitorType state transitions from 'viewer' to 'buyside'... A ...

Using a uibCollapse within a nested directive element may not function as expected

Whenever I try to click on my custom directive, the elements that are supposed to expand remain collapsed. To ensure that the click event is actually triggered, I have specified a size in the css for the .btn class. // index.html <body ng-controller=" ...

The deleteCell function will not properly function when directly targeting selected table rows (trs)

I'm currently facing an issue while trying to dynamically access a specific tr element. Although I believe that the tr is being selected, when attempting to use the deleteCell method, it gives an error stating that the object does not have such a meth ...

audio enhancement in a web-based game

I'm having trouble getting a sound effect to play consistently in my game whenever there is a hit. Sometimes the sound plays, other times it does not! Here is the code I am using: <script> var hitSound = new Audio(); function playEffectSound ...

Tips for updating text in a freshly opened window using JQuery or JavaScript

I have a function that is triggered by a button click to open a new window or tab, display an alert, and update text. Here is the code snippet: function nWin(p) { var setStyle = "<style rel='stylesheet'>\ .vTop {\ ...

Retrieving Text Between HTML Tags Using jQuery

Disclosure: I am fully aware of the messy HTML code in this legacy application. Unfortunately, due to its extensive dependencies, making any changes to the HTML structure is not feasible. Despite the circumstances, here is the code snippet at hand: <t ...

What is the best way to send an object to its matching element?

Imagine having 4 labels and 4 buttons aligned next to each other. While it's common to update the label values by their corresponding button IDs, is there an alternative method using objects or references? <button onclick="myFunction()">Set dem ...

Simulate a failed axios get request resulting in an undefined response

I'm having an issue with my Jest test mock for an axios get request, as it's returning undefined as the response. I'm not sure where I might be going wrong? Here is the component with the axios call: import {AgGridReact} from "ag-grid- ...

Implementing Dynamic Script Injection in Angular Controllers for Enhanced HTML Functionality

I'm a total beginner when it comes to Angular and frontend development, so please bear with me if my question seems basic: In my controller, I have the following code where I am populating the $window.user data that is being used in the script [2] ad ...

Display or conceal elements using the unique identifier selected from a dropdown menu in JavaScript

I have been searching the internet for a solution to my issue but nothing seems to be working. Here is the problem: Unfortunately, I cannot modify the TR TD structure and am unable to use DIVs. I am trying to dynamically display certain TD elements based ...

Warning displayed on form input still allows submission

How can I prevent users from inserting certain words in a form on my website? Even though my code detects these words and displays a popup message, the form still submits the data once the user acknowledges the message. The strange behavior has me puzzled. ...

Implement React-intl into the designated placeholder within the object

Currently facing an issue with the const inputProps in my code. I attempted to integrate React-intl into the react-autosuggest placeholder input, but now the placeholder text displays as: [Object object]. The getStepContent function is defined as follow ...