Troubleshooting: Unable to make Ajax POST call in Asp .Net Core 2.2 Razor Pages

Despite my experience with ajax in razor pages, I am struggling to understand why this particular script is not functional. Each time I run it, I encounter a 400 error in the developer tools. It appears that the page handler is not being reached at all.

<script>
     $.ajax({
                    url: "/Account/Users/Index?handler=Delete",
                    type: "POST",
                    data: {
                        id: id
                    },
                    success: function () {
                        swal("User Disabled!", {
                            icon: "success",
                        });
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        swal("Failed to connect to server. Please try again later.");
                    }
                });
</script>

Concerning the page handler:

  public async Task<IActionResult> OnPostDeleteAsync(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var user = await _context.Users.FindAsync(id);

        if (user != null)
        {
            user.IsActivo = false;
            _context.Users.Attach(user).Property( u => u.IsActivo).IsModified = true;
            await _context.SaveChangesAsync();
        }

        return RedirectToPage("./Index");
    }

I have experimented with different URL variations, but none seem to be effective. I am unable to identify any errors within the code...

EDIT

It appears that the issue may lie within the validation of the anti-forgery token on the razor page.

After adding Ignore Anti forgery Token to the page model, the script now runs smoothly.

Answer №1

If you're experiencing issues with the anti-forgery token causing problems, don't worry - there is a solution! When working within a form in asp.net core, the hidden input containing the token is generated automatically for you. However, if you are not using a form, you can manually add the token by calling @Html.AntiForgeryToken(). But that alone won't fix the Bad Request problem. You need to include the token in your ajax call like this:

$.ajax({
    url: "/Account/Users/Index?handler=Delete",
    type: "POST",
    beforeSend: function (xhr) {
        xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
    },
    data: {
        id: id
    },
});

Don't forget to also include this line in your Startup.cs file for added security:

services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");

Answer №2

When it comes to mapping URLs, it typically involves the controllerName/actionName/ structure. In your specific case, you can try using:

url: "/Account/OnPostDeleteAsync"

or

url: "/Users/OnPostDeleteAsync" If your URL is correct, consider using the [FromForm] attribute as shown below:

public async Task<IActionResult> OnPostDeleteAsync([FromForm]int? id)

I hope this information proves helpful

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

Stripping out categories from a text

After receiving content from an input, I save it in a variable named 'content' My next task is to modify this variable by removing classes from any img tags. Here's what I've attempted: $('img', content).removeClass('c1 ...

Using Javascript/React to filter an array by a specific value

{ "team_group": ["Alex Smith", "Jake Brown", "Sarah King"], "group_data": { "Alex Smith": { "status": "member" }, "Jake Brown": { "status": &qu ...

Is there a way to retrieve solely text from a Spring servlet?

So, here's what's going on - I've got a single page application that needs to call a servlet using an Ajax object and then display the returned text on the webpage. Here's how I'm tackling it: index.html <!DOCTYPE html> &l ...

Received an empty response while making an AJAX request - ERR_EMPTY_RESPONSE

I am trying to fetch real-time data from my database using Ajax, but I keep encountering an error. Here is the code snippet: <script> window.setInterval( function() { checkCustomer(); //additional checks.... }, 1000); function che ...

HTML coding for a collapsible side panel

Seeking a straightforward JavaScript solution to generate a side panel that hides after a specific action, such as clicking on a designated area. Similar to the sliding panels demonstrated in this example, but appearing from the left side instead of top ...

Displaying the server's feedback upon successfully uploading a file onto the server

I am utilizing an HTML5 input control that allows users to upload a .csv file: <input id="ImportFile" type="file" name="ImportFile" data-val="true" data-val-required="Please select a file" title="Browse for a file to upload" /> This input control i ...

Establishing the default value of an input field in Angular by referencing another field

Within an Angular (1.5) setting, I am confronted with a form containing two input sections: ID URL The requirements are as follows: If the ID section remains vacant, the URL field should likewise be left empty. If the URL area is entered manually, it ...

What is the best way to specify the JSDoc types for this.field within the Mocha TestContext during the before() hook, in order to provide clarity for other it() tests as well as IntelliJ?

I am looking for IntelliJ, or a similar IDE like WebStorm or VSCode, to provide auto-complete for the fields I define in my Mocha.js before() hook within my test context. Furthermore, I want to have access to the auto-complete documentation of those fields ...

Axios is capable of performing GET requests to a specific URL, however, it is unable

I am currently developing a React app Within one component, I have successfully implemented a GET request: https://i.sstatic.net/LnRHm.png In another component, I am working on a POST request: https://i.sstatic.net/pQVTU.png However, when sending the ...

Delete the current code within the specified div element

Objective: The goal is to ensure that any HTML syntax code or data inside the specified <div id="feedEntries"></div> element is removed, leaving it empty. Issue: What specific syntax is required to remove all content within <div id="fe ...

What is the most effective method for pausing execution until a variable is assigned a value?

I need a more efficient method to check if a variable has been set in my Angular application so that I don't have to repeatedly check its status. Currently, I have a ProductService that loads all products into a variable when the user first visits the ...

How to send a GET request to an Asp.Net Core Mvc controller using Ajax

I am a beginner in MVC and currently working on a homework project that requires making an AJAX call to a controller to retrieve data from the database. Despite receiving a 200 HTTP code, I am encountering issues with printing the contents of the "success" ...

Implementing the currency filter on an input field using AngularJS

Hey there! I've noticed that when using span tags, I can apply the money filter like this: <div ng-repeat="item in items"> <span> {{item.cost | currency}} </span> </div> Now I'm curious if it's possi ...

A guide on retrieving styled text from a database and displaying it in TinyMCE

I am encountering an issue where I need to retrieve formatted text from a database and display it in my TinyMCE editor. The content stored in the database looks like this: <p style="text-align: justify;"><strong>Zdrav&iacute;m</strong ...

Is there a way to iterate through an object while capturing the index of each element and then saving it into an array?

After attempting the following code, I am only receiving a single value as output. Object.keys(yelpResults).map((key) => { return setRestaurantIndexes(restaurantIndexes.concat(key)); }); ...

How can I retrieve all element attributes in TypeScript using Protractor?

I came across this solution for fetching all attributes using protractor: Get all element attributes using protractor However, I am working with TypeScript and Angular 6 and struggling to implement the above method. This is what I have tried so far: im ...

Using the Facebook API to post feeds asynchronously in a repetitive loop

I am currently in the process of developing a Facebook ASP.NET C# application. At this point, the application is storing users' access tokens in a database along with their expiration time and Facebook ID. For instance, when a user passes authentica ...

Load the next set of results by transferring the content into a div

After my initial search yields perfect results, I encounter an issue when searching for the second time. The second set of results is appended to the first set, resulting in a confusing display. If I try to use .html(), only the last value is printed. Is ...

What is the proper way to send a parameter with an Ajax.request call in jQuery?

Is there a way to pass a parameter when making an Ajax request and then retrieve it in the .done function upon a successful request? var requestFeed; requestFeed = Ajax.request(url, { method: 'GET', type: ...

Having trouble with nested requests and appending using Jquery or JavaScript?

Greetings everyone, I want to apologize in advance for any spelling errors or mistakes in my message. I struggle with dyslexia and other learning difficulties, so please bear with me. I am using this time during lockdown to learn something new. This is my ...