Skip to content Skip to sidebar Skip to footer

Mvc - Multiple Parameter Ajax Call

I am trying to send 2 parameters to the controller from the View using an ajax call. This function worked earlier when I was only using 1 parameter but it no longer is working sin

Solution 1:

Two issues

1) Your action method parameter name is rowId, but you are sending roleId

2) The JSON.stringify method creates a string representation of the JavaScript object you pass to it. With this method, you are sending a JSON string of the object as the data property of the $.ajax method option. When sending a JSON string of your JS object, you should specify the contentType property of the option to application/json.

$.ajax({
    type: "POST",
    url: '@Url.Action("Delete_Role", "Admin")',
    dataType: 'json',
    data: JSON.stringify({
        rowId: '@Guid.NewGuid()', // dummy GUID for testingapplicationId: '@Guid.NewGuid()'
    }),
    contentType:"application/json"
}).done(function (response) {
    console.log(response);
}).fail(function() {
    console.log("Error on Deletion");
});

Now $.ajax will add the request header Content-Type to the call with the value application/json. As part of model binding, the default model binder will read this request header value and then decide to read the data from the request body(Request payload).

Also since you are not sending a complex object, you do not need to send the JSON string version. Simply pass the JavaScript object as the data property and $.ajax will send this as form data.

$.ajax({
    type: "POST",
    url: '@Url.Action("Delete_Role", "Admin")',
    data: {
        rowId: '@Guid.NewGuid()',  // dummy GUID for testingapplicationId: '@Guid.NewGuid()'
    }
}).done(function (response) {
    console.log(response);
}).fail(function() {
    console.log("Error on Deletion");
});

In this case, $.ajax will send application/x-www-form-urlencoded as the Content-Type request header value and model binder will be able to read it properly and map it your parameters.

You can also remove the dataType in ajax call ( which I did in the second code snippet). jQuery ajax will guess the proper type from the response header and use that to further pars the data is received from the server call. In your case, you are calling the Json method to return JSON response from your action method, which will send the application/json as the Content-Type header value.

Post a Comment for "Mvc - Multiple Parameter Ajax Call"