Home > Software engineering >  Multiple arguments failing in ajax in a C# mvc app - More info added
Multiple arguments failing in ajax in a C# mvc app - More info added

Time:04-06

I'm missing something here. This is my controller method

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

This is my button def

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

This is 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 hit and the arguments are populated. I've hacked around and determined that the issue is with the AJAX data field. If I have no arguments in the controller, I get to my break point, so confident the error is in my data line.

If I edit my JS Function to look like this

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 get an error returned in markup, with the title tag saying Invalid JSON primitive: personID. Note that I am passing the obj in the Data element.

If I change the data line to

data: JSON.stringify(obj),

I then get mark up back with the title containing An item with the same key has already been added. In both of the above scenarios, my controller break point is never hit.

I'm running VS 2022, sp mostly newer libraries I guess.

Any help or pointers would be immensely appreciated.

Cheers

J

CodePudding user response:

since you are using json you will have to read data from body. Only one input parameter can be get from body in action. So you need a view model

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;}
}

and action

public ActionResult SubmitSweep([FromBody] ViewModel model)
{

}

or if you want to keep the action as it is you have to remove contentType:json from you ajax and don't stringify object

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

CodePudding user response:

Solved it, thought I'd share it just in case somebody else has the same brain failure I've just wasted days on!

The problem was with my controller method signature. I changed it from what I had in the original question above, to

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

Changed the parameter names in my JS function to match like this

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);
            }
        });
    }

Now it works. Clearly JS is case sensitive as is C#, but the posted URL "isn't". Hopefully this will help somebody who stupidly creates the same issue for themselves. Lesson remembered, always use meaningful variable names!

J

  • Related