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 method for obtaining the CSS text content from an external stylesheet?

I've spent countless hours trying to achieve the desired results, but unfortunately, I haven't been successful. Below is a summary of my efforts so far. Any helpful tips or suggestions would be greatly appreciated. Thank you in advance. Upon rec ...

Utilizing ES6 imports with module names instead of paths

Is there a way to import modules using just their name without the full path? For instance, can I simply use: import ViewportChecker from 'viewport-checker'; instead of import ViewportChecker from '../ViewportChecker'; I'd ...

Spirit.py navigates using javascript

Having trouble with Ghost.py. The website I'm trying to crawl uses javascript for paginated links instead of direct hrefs. When I click on the links, selectors are the same on each page so Ghost doesn't wait since the selector is already present. ...

Assign the physics settings to a variable within the A-frame

Exploring A-frame () for my scene creation has been exciting. I am curious about how I can dynamically adjust the physics in my virtual world using the A-frame physics component. The goal is to have the physics within my scene be determined by a variable c ...

Tips for resolving the issue of "Warning: useLayoutEffect does not have any effect on the server" when working with Material UI and reactDOMServer

Encountering an issue with ReactDOMServer and Material UI Theme Provider. Everything seems to be functioning properly, but a persistent error keeps appearing in the console: Warning: useLayoutEffect does nothing on the server, because its effect cannot be ...

Fixing the Jquery Clone Bug

Recently, I came across a jQuery clone plugin that is designed to fix the values of cloned textarea and select elements. This code snippet showcases how it works: (function (original) { jQuery.fn.clone = function () { var result = ori ...

Tips for managing Express.js callbacks and modifying an object's property from within a function

I am currently working with two JavaScript files. I have successfully retrieved data from MongoDB using the method bookDao.getActiveBookByCategoryId(). The Issue I Am Facing: Within the categoryDao.js file, I am attempting to update the resultJson.book_c ...

Integrate the perfect-scrollbar jQuery plugin into RequireJS

Recently, I decided to explore RequireJS for my projects but I am still trying to understand its functionalities. I'm currently attempting to incorporate perfect-scrollbar, specifically the jQuery version, into my work. Here's a snippet from my ...

Unlocking Iframe Mode in CKEditor 4

I've encountered a difference between CKEditor 3 and CKEditor 4. In CKEditor 3, when I call the method CKEDITOR.replace('#textAreaId'), it wraps the editor in an iframe. However, in CKEditor 4, when I call the same method (not inline), the i ...

create a recurring design wallpaper within the TinyMCE editor

One of my functions alters the background of the tinymce editor. However, I am interested in having a wallpaper repeat in a similar fashion to background-repeat: repeat; in CSS. How can I achieve this? Here is the function: function SettinymceImage(bg_i ...

Instructions for developing an HTML element slider using mouse dragging

I've come across plenty of slider plugins that either only allow clicking to view the next image, or if they do support mouse drag or touch capabilities, they are limited to images. Does anyone know of a plugin or method to create a mouse drag slider ...

Seeking advice on removing the initial blank space from a dropdown value in Angular.js

I have a deeply thought-out logic that I would like to illustrate with an example. However, in order to present it effectively, I am looking for suggestions on how to simplify the process without relying too heavily on the controller. <select class="fo ...

Prevent the browser back button from being used in a web application that requires CLIENT_CERT authentication

My website utilizes CLIENT_CERT JAAS authentication and is compatible with IE7. After logging out, when I return to the home page and click on the back button, I want to stay on the same non-secure page. I have been able to achieve this using the history. ...

What causes offsetHeight to be less than clientHeight?

INFORMATION: clientHeight: Retrieves the height of an element, taking into account padding offsetHeight: Obtains the height of an element, considering padding, border, and scrollbar Analyzing the Data: The value returned by offsetHeight is expected to ...

Allow images to be uploaded using the browser-policy package in Meteor

Can anyone help me figure out how to use Sir Trevor JS in Meteor for uploading images without encountering this error message? When attempting to load the image 'blob:http%3A//localhost%3A3000/a28ef7dc-ee51-4290-9941-6b8fc317e685', I am receivin ...

Iterating over an array of numbers in AngularJS

I have an array of numbers $scope.N = [1,2,3,4]. I want to loop through this array in my HTML code using ng-repeat, similar to the example with JSON ng-repeat. <div ng-repeat="num in N"> {{num}} </div> How can I achieve this with a ...

What is the solution to preventing Angular 1.3 ngMessages from affecting the size of my form?

Hey there, I'm diving into front-end design for the first time. My issue is with a form that I want to use ng-messages for validation error messages. Currently, my form's size changes depending on whether there are errors displayed or not, and it ...

Encountering the "v_isRef": true flag while utilizing Vuex within a composition function

I encountered an unexpected outcome when using the loginString() function in my template. It seems that there is a need to include .value in templates, which I thought wasn't necessary. { "_dirty": true, "__v_isRef": true, "__v_isReadonly": true } ...

The jQuery autocomplete feature with typeahead suggestions fails to appear following a successful AJAX request

I am currently using typeahead.js to incorporate tags into my multiple input setup. The tagging function works as expected, however, I am facing an issue where the autocomplete suggestions are not appearing. Is there a solution to fix this problem? Despit ...

Display or conceal elements in Angular based on multiple conditions

Looking to develop a functionality where an array of objects can be shown or hidden based on specific filters. The desired output should be as follows: HTML CODE: Filter: <div (click)="filter(1)"> F1 </div> <di ...