-1

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)" class="btn btn-secondary" 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

Jim Tench
  • 123
  • 8

2 Answers2

0

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, 
           ...
Serge
  • 40,935
  • 4
  • 18
  • 45
  • Sorry, but I don't think this is right. This feels like you're suggesting a round trip to the server, this is not something I want. The initial page load is slow, as I'm dependent on a third party API, which is very slow, so I need to avoid page reloads, hence the AJAX. – Jim Tench Apr 03 '22 at 12:25
  • @JimTench I don't know what is inside SubmitSweep, you don't need to return anything if you don't need. Where can you see page reload? You can' t reload page using ajax – Serge Apr 03 '22 at 12:33
  • I've edited the question, hopefully ti makes more sense now. I suspect what I need is a tutorial on AJAX maybe :-( – Jim Tench Apr 04 '22 at 13:43
  • @JimTench And what is your problem now? You will still have the empty action input parameters. Why you don't follow my answer? – Serge Apr 04 '22 at 13:48
  • Because I believe your answer to be wrong. Adding a C# model makes no sense as this is a pure javascript AJAX call. I could very easily change my backend from an MVC app, to an API and write my front end in pure java and would have the same issue. I've seen several stckoverflow questions around this, but none of those solutions work for me. Here is one example - https://stackoverflow.com/questions/1916309/pass-multiple-parameters-to-jquery-ajax-call – Jim Tench Apr 04 '22 at 14:30
0

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

Jim Tench
  • 123
  • 8