0

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 since I added a second.

Javascript with ajax:

function DeleteRole(roleId) {
    var confirmation = confirm("Are you sure you want Delete this Role");
    if (confirmation) {
        $.ajax({
            type: "POST",
            url: '@Url.Action("Delete_Role", "Admin")',
            dataType: 'json',
            data: JSON.stringify({
                roleId: roleId,
                applicationId: $('#AppList').val()
            })
        }).success(function (response) {
            if (response.success) {
                alert(response.responseText);
                $(".k-grid").data("kendoGrid").dataSource.read();
            }else {
                alert(response.responseText);
            }
        }).error(function() {
            alert("Error on Deletion");
        });
    }
}

MVC - controller method(information isn't getting here at all)

   [HttpPost]
    public JsonResult Delete_Role(Guid rowId, Guid applicationId)
    {
        var users = new UserStore().ReadForAppRole(applicationId, rowId);

        if (users.Any())
        {
            return Json(new { success = false, responseText = "Users's Currently Exist Within this Role" },
                JsonRequestBehavior.AllowGet);
        }

        new RoleStore().RemoveRole(applicationId, rowId);

        return Json(new { success = true, responseText = "Role Successfully Deleted" },
            JsonRequestBehavior.AllowGet);
    } 
4
  • 2
    you have a rowId vs roleId the variable names need to match also not sure what happens if a non valid guid is passed - think it may just come in as null Commented Nov 19, 2018 at 16:17
  • Have you attempted to just change the end URL to a fake location or console logging the ajax request using a get global posts? And @Pete his remark fits too - the params could also be an issue but I personally would first attempt to find out if the post even occurs and then onward Commented Nov 19, 2018 at 16:18
  • 1
    you're sending a string of JSON but not telling the server that via the content-type. OTOH there's no particular need to send it as JSON, if you just remove the stringify operation then jQuery will form-encode it for you and MVC shouldn't have any trouble reading it. Commented Nov 19, 2018 at 16:21
  • shouldn't delete be using [HttpDelete]? Commented Nov 19, 2018 at 16:26

1 Answer 1

2

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 testing
        applicationId: '@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 testing
        applicationId: '@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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.