Noahm888
Noahm888

Reputation: 123

Ajax call is passing controller name and method name instead of data

I am running into some trouble with my ajax call. Here is the controller code:

[Route("RatingInfo/HandleRequest")]
[HttpPost]
public ActionResult HandleRequest(Dictionary<string, string> textBoxValues)
{
    var result = CreateJson(textBoxValues); // This is a simplified example

    return Json(result);
}

And here is my Jquery/ajax (Razor syntax):

function PassData () {
    var data = {};
    $('.divCell input').each(function (index, item) {
        var id = $(item).attr('id');
        var value = item.value;
        data['dictionary[' + index + '].Key'] = id;
        data['dictionary[' + index + '].Value'] = value;
    });

    $.ajax({
        url: '@Url.Action("HandleRequest")',
        type: 'POST',
        dataType: 'JSON',
        traditional: true,
        data: data,
        sucesss: function (result) {
            alert('Success');
        }
    })
}

The idea here is to get the data from each textbox and pass it back to the server as a Dictionary with the id as the key and value as, well, the value.

Stepping through the Chrome debugger, the JS data object is built successfully.

From the debugger:

 Local
 data: Object
 dictionary[0].Key: "Address"
 dictionary[0].Value: "123 Main St"
 dictionary[1].Key: "ZipCode"
 dictionary[1].Value: "99999"
 dictionary[2].Key: "Phone1"
 dictionary[2].Value: "(555) 555-5555"
 ...
__proto__: Object

However, when the data is passed back to the controller, the values inside textBoxValues does not contain the passed data. Rather, it contains two key/value pairs with keys controller and action and values the names of the controller and action.

From the Visual Studio debugger:

 textBoxValues = Count = 2
 [0] = {[controller, RatingInfo]}
 [1] = {[action, HandleRequest]}

How can I get Jquery to pass the data rather than the controller/action names? I am confused as to how this can even happen in the first place. Any help would be appreciated.

Upvotes: 1

Views: 2347

Answers (1)

ragerory
ragerory

Reputation: 1378

UPDATE

Sorry, I had put wrong code in.

The reason why this was not working is because the name of the parameter was incorrect, giving you a mismatch.

The below will work for you. Notice the name of dictionary is changed to your parameter textBoxValues:

function PassData() {
    var data = {};

    $('.divCell input').each(function (index, item) {
        var id = $(item).attr('id');
        var value = item.value;
        data['textBoxValues[' + index + '].Key'] = id;
        data['textBoxValues[' + index + '].Value'] = value;
    });

    $.ajax({
        url: '@Url.Action("HandleRequest")',
        type: 'POST',
        traditional: true,
        data: data,
        sucesss: function (result) {
            alert('Success');
        }
    })
}

Upvotes: 2

Related Questions