Exploring the Wonder of MVC with Ajax Calls Handling Multiple Parameters

I've been struggling to send 2 parameters from the View to the controller using an ajax call. Everything was working fine when I had only one parameter, but as soon as I added another, the function stopped working.

Below is the Javascript code with ajax:

function DeleteRole(roleId) {
    var confirmation = confirm("Are you sure you want to 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 during Deletion");
        });
    }
}

Here is the MVC controller method (it seems like no information is reaching here):

   [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 = "There are currently Users within this Role" },
                JsonRequestBehavior.AllowGet);
        }

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

        return Json(new { success = true, responseText = "Role successfully deleted" },
            JsonRequestBehavior.AllowGet);
    } 

Answer №1

Two points to consider

1) The parameter name in your action method is rowId, but you are passing roleId

2) When using the JSON.stringify method, it creates a string representation of the JavaScript object being passed to it. In this case, you are sending a JSON string of the object as the data property within the $.ajax method option. To ensure proper handling, specify the contentType property as 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 with $.ajax, the request header Content-Type will be added to the call with the value set to application/json. This allows the default model binder to read the data from the request body based on this header value.

If you are not sending a complex object, there's no need to stringify it into JSON. Simply pass the JavaScript object as the data property and $.ajax will handle it 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 scenario, $.ajax will send the Content-Type request header as

application/x-www-form-urlencoded</code, which the model binder can interpret correctly and map to your parameters.</p>

<p>You can also omit the <code>dataType
in the ajax call (as shown in the second code snippet). jQuery ajax will determine the response type from the header and parse the received data accordingly. Since your action method returns JSON, the Content-Type header will be set to application/json.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process of converting the timing from my stopwatch to a standard time format?

I am currently working on a stopwatch project where I log the time into an array. However, when I try to use Math.min(array) or Math.max(array), it returns NaN (not a number). The time format for the stopwatch is like 00:00:15.91 which is not recognized as ...

Unable to locate the JavaScript/jQuery key

Struggling with a dictionary in JavaScript being passed to a function in Django. Despite the key existing, I'm getting an error saying 'key message not found'. As a newbie in Javascript and JQuery, I must have made a simple mistake somewhere ...

Material-inspired Design Device Compatible DIV slide with JS, JQuery, and CSS

My goal is to achieve something similar to this: Desired Live Website I am looking for a feature where clicking on the div will slide in content from the right, load an external page inside it, and close when prompted. The slider div should be device c ...

Unable to remove data once it exceeds 10 entries while using AJAX, jQuery, and JavaScript/PHP

I am having an issue where I can insert data into the first 10 rows and delete any of them successfully. However, when I try to insert data starting from the 11th row, I am unable to delete any rows past the 10th. UPDATE: The deletion function does not wo ...

Load select box with options upon document load

After the document loads, I want to populate a select box with values from my database using ajax and jQuery. Can someone help me identify what's wrong with my code? <select class="form-control sec" id="sec" name="sec"> <option value="s ...

AJAX - Implementing a delay in displaying AJAX results

My search function uses AJAX to retrieve data from the web-server, and I am trying to implement a fade-in animation for each search result. I want the results to load and fade in one by one with a slight delay between them. Currently, it seems like all th ...

Struggling to locate the correct setup for .babel and react-hot-loader

I am currently utilizing babel 7. In their documentation, they specify that the new naming convention for plugins should include the @babel/ prefix. The recommended React-hot-loader babelrc configuration is as follows: { "plugins": ["react-hot-loader/ ...

Ways to disseminate arguments when dealing with an array of arrays in JavaScript

Struggling to pass an array as arguments into the join method on path in node, but hitting a roadblock: var path = require("path"); var paths = [__dirname]; var userInput = ["app", "js"]; paths.push(userInput); var target = path.join.apply(null, paths); ...

When attempting to send JSON data using Ajax, you may encounter an issue such as receiving an error message

I am currently working on developing a login with Facebook application using Codeigniter. My challenge is passing JSON data to my controller through AJAX. This is the code snippet I am using: var data = JSON.stringify(response); alert(data); $.ajax ...

Issue with Backbone Event Dropping Functionality

I am facing an issue with my dashboard that has two backbone Views. One of the views consists of various drop zones while the other contains items with draggable="true". Surprisingly, the drop event is not being triggered in these drop zones; however, they ...

Using AJAX POST for real-time validation of usernames and email addresses

Creating a basic form with AJAX and jQuery to validate the username and email address before submitting: <body> <div> <h5> Registration </h5> <hr /> <div> Username: <input type="text" size="32" name="membername" ...

Ways to utilize a string as an object?

Hey there! I'm just getting started with software development and currently working on an application using React Native. The backend is sending me a large data set, but here's a snippet of it. My challenge is that I want to access the first ele ...

Display the source code of an HTML element when clicked

Is there a way to show the source code of an element on a webpage in a text box when that specific element is clicked? I am wondering if it is feasible to retrieve the source code of an element upon clicking (utilizing the onClick property), and subseque ...

Javascript behavior during execution can vary from what is observed during debugging

I'm currently facing an issue while trying to debug a script. Everything seems to work fine in debug mode, but not during runtime. Here's the JavaScript function causing trouble: function Add() { ... $('#Value').val($('#V ...

Using PM2 to Manage Your PHP Scripts in Cluster Mode

Currently, I have been effectively managing single instances of PHP daemons with PM2, and so far everything is running smoothly! When it comes to managing Node.js/IO.js apps with PM2, I can easily launch them in cluster mode without any issues. However, t ...

Acquire the content of a nested element using jQuery

I have a navigation list with separate headlines and text for each item. The goal is to switch the main headline and paragraph of text when hovering over a navigation item. CodePen Example Currently, my code displays all text. I only want to display the ...

Incorporate a fresh key-value pair into the Redux Toolkit's state

I am currently working on an application that enables users to create and modify recipes. To manage the state, I have chosen to utilize React Toolkit and Redux. Here is an example of the state structure: const ingredients = [ { ingredientName: &apos ...

Implementing API calls in C# with the help of AngularJS

Hey there! I am currently accessing my API by using the code snippet below: $http.get('/api/controller/method?param=value'). then(function (response) { if (response.status == 200) { console.log(resp ...

Changing the size of an iframe and closing it by pressing the ESC

I am developing an application that requires the ability to resize an iframe. When the user clicks the "Full Screen" button, the iframe should expand to occupy the entire screen. The iframe should return to its original size when the user presses the "Es ...

How can I reduce the burden of dependencies on users with a pre-built NPM package?

I recently took over maintenance of an NPM package. It has a unique setup where the main file is located in the 'dist/' directory and it's built using webpack (via 'npm run build'). While this works for us, installing this package ...