Error Occurs When Attempting to Delete in ASP.NET MVC

I am encountering an issue while attempting to delete something, as it is displaying the following error message:

"Error: Unknown Action"

Below is my controller code:

[Authorize(Roles = "Admin, Staff")]
        [HttpPost]
        [ValidateAntiForgeryToken]

public ActionResult Delete(int? id)
        {
            string result = null;
            try
            {
                if (id == null)
                {
                    result = HIQResources.errorMessageUnknownAction;
                    return new JsonResult { Data = result };
                }

                StudentViewModel vm = new StudentViewModel();
                StudentDetail studentDetail = studentManager.GetStudentDetailById(id.Value);
                if (studentDetail == null)
                {
                    result = HIQResources.errorMessageUnknownRecord;
                    return new JsonResult { Data = result };
                }


              int deleteResult = studentManager.Delete(id.Value);

                if (deleteResult == 1)
                {
                    vm.Alert.SetSuccessMessage(HIQResources.messageOperationSuccess);
                    TempData["alert"] = vm.Alert;

                    result = HIQResources.messageOperationSuccess;
                    return new JsonResult { Data = result };
                }
                else
                {
                    vm.Alert.SetErrorMessage(HIQResources.errorMessageUnableToExecuteOperation);
                    TempData["alert"] = vm.Alert;


                    result = HIQResources.errorMessageUnableToExecuteOperation;
                    return new JsonResult { Data = result };
                }

            }
            catch (DbUpdateException ex)
            {
                Log.AddLogRecord(LogManager.LogType.Warning, LogManager.LogPriority.Low, LogManager.LogCategory.Teacher, ex.Message, ex.StackTrace, base.GetLoggedUser());

                result = HIQResources.errorMessageUnableToDeleteRecord;
                return new JsonResult { Data = result };
            }
            catch (Exception ex)
            {
                Log.AddLogRecord(LogManager.LogType.Error, LogManager.LogPriority.High, LogManager.LogCategory.Inscription, ex.Message, ex.StackTrace, base.GetLoggedUser());

                result = HIQResources.errorMessageExceptionOccurred;
                return new JsonResult { Data = result };
            }
        }

Here is my Javascript snippet:

 $('#ModalDeleteButton').on("click", function (e) {
                var token = $('input[name="__RequestVerificationToken"]').val();
                $.post("/Student/Delete/",
                    {
                        __RequestVerificationToken: token,
                        id: id
                    },
                    function (data) {
                        $('#myModal .close').click();
                        var baseurl = '@Url.Action("Index")';

                        var url = baseurl + "?message=" + data;
                        window.location.href = url;
                    });
            });

I require more specific details regarding this error. The controller and JavaScript seem correct to me, so I am unsure of what the issue could possibly be.

Answer №1

Ensure that when using the $.post function, you include the [HttpPost] attribute above the method definition to specify it as a POST request. Otherwise, it will default to assuming a GET request, leading to an "unknown" action.

UPDATE:

To address this issue, consider replacing your $.post with the following $.ajax snippet:

$.ajax({
    type: "POST",
    data: {
        __RequestVerificationToken: token,
        id: id
    },
    success: function(data) {
        $('#myModal .close').click();
        var baseurl = '@Url.Action("Index")';

        var url = baseurl + "?message=" + data;
        window.location.href = url;
    }
});

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 best way to create an HTML5 Range that gracefully degrades?

I want to incorporate the <input type='range' /> element from HTML5 for modern browsers and fallback to a <select /> if needed. Since I am working with Ruby-on-Rails, as a last resort, I could implement something similar to this on th ...

What is the step-by-step process for executing the following functions: 1. magnify -> 2. spin 360 degrees -> 3. restore to original size before magnification -> 4. switch colors on and

Can you show me a demo featuring the following functions in order: 1. enlarge -> 2. rotate 360 degrees -> 3. resize to original size -> 4. change color (toggle) $(document).ready(function() { $('.tlist td div').click(function() { ...

Top-notch Java EE Ajax framework

As a newcomer to Java EE, I am looking for a framework that can simplify AJAX for me. Currently, I am using the dojo toolkit to draw graphs, but I want to make these graphs updatable through AJAX. Is there a framework that facilitates AJAX callbacks and al ...

Trigger a JavaScript function from ASP.NET code-behind

Here is a JavaScript function I've created: function returnToParent() { var oArg = new Object(); var oWnd = GetRadWindow(); oArg.ReturnValue = "Submit"; oWnd.close(oArg); } This is how I call the func ...

How can you automate the execution of unit tests in Angular before pushing changes to Git?

There have been instances in Angular projects where the unit tests are triggered every time a build is carried out, as well as when running the git push command. In case any tests fail during either of these commands, the process halts until all unit tes ...

What is the best method for organizing an array of objects (classes)?

I am attempting to sort an array of objects using the Array.Sort method, but I keep encountering an InvalidOperationException. I have learned that when sorting a complex object, I need to implement the IComparable <T> comparison interface, but I am s ...

The error message "Error: cannot read property ‘setDirtyAttribute’ of null" may be encountered when attempting to use the method YourModel.create({...}) in ember-typescript-cli

Encountering the error cannot read property 'setDirtyAttribute' of null even when using YourModel.create({...}) in ember-typescript-cli to instantiate an EmberObject. Model: import DS from 'ember-data'; import {computed} from "@ember/ ...

Tips for showcasing a restricted amount of data with Angular.js

I've been exploring different ways to limit the results using limitTo, but unfortunately, I'm encountering unexpected issues. Currently, the entire list is being displayed when I only want to show 8 key-value items in a 4/4 block format. You can ...

Developing a cancellation feature for the Valums file uploader

I'm in the process of enhancing my uploader by adding a cancel button. I want this button to be displayed separately from the filuploader.js template, preferably in its own div along with a progress bar to provide detailed information about the file b ...

How can I resolve a JavaScript issue that occurs when accessing a property within the same object?

Displayed below is a snippet from a much larger JavaScript object within my project. Thousands of lines have been omitted to focus solely on the area in question... Line 6 is specifically where the issue lies. Here's a concise example involving Java ...

Learn how to automatically update data in Vue JS after making a 'POST,' 'DELETE,' or 'PUT' request in Vue JS 2

Whenever I send a 'POST' or 'DELETE' request, the data doesn't update automatically. I have to manually reload the page to see the updated information. Is there an easy way to refresh the data after making any 'POST' / &a ...

Issues with the audio on ExpressJS video streaming can be quite vexing

After multiple attempts to run an ExpressJS web server that serves videos from my filesystem, I've encountered a frustrating issue. Whenever a video is played, there are constant popping sounds and eventually the audio cuts out completely after 3-10 m ...

Is it possible to create a button function in HTML that can alter the CSS image tag?

Is there a way I could create a function that can retrieve a value, update an image source, and then incrementally select another value? It would be incredibly helpful if you could provide a reference where I could learn how to do this or explain it in det ...

Working with JSON responses in ASP.NET

Being a PHP Developer with limited knowledge of asp, I am working on a portal in PHP that requires an ajax post to an asp page on an external server. The response from the asp page is formatted like this: OK|some_id|some_name|some_id|0|1|||some_name|some_ ...

Ajax undoes any modifications enacted by JavaScript

When using ajax, I trigger an OnTextChangedEvent. Before this event occurs, there is a Javascript function that validates the input field and displays text based on its validity. However, once the Ajax is executed, it resets any changes made by the Javascr ...

Is there a way to retrieve the value of a Promise?

When making a call to a Promise API for returning from an AJAX request, I would like to have the return value in the then() function structured as follows: function get_data(url, id) { return new Promise(function (resolve, reject) { xmlHttp.open("GET" ...

What is the best way to sort through received JSON information?

I am attempting to create a simple command that retrieves information from imgur, locates the images, and then randomly selects which photo to display. The issue I am encountering is my inability to filter the responses based on specific criteria. Below is ...

open() the html file containing dojo elements

I have a simple Dojo chart that functions perfectly in a separate document. However, here lies the issue, When I use $('#result').load('dojo.html'); to import the file, nothing occurs - the page does not load the graph. On the other h ...

Get the maximum width in pixels through JavaScript when it is specified in different units within the CSS

I'm looking to retrieve the max-width value in px from CSS for use in a JavaScript code. The challenge is that this value might be specified in different units in the CSS file. Any suggestions on how to achieve this using JavaScript? const element = ...

React-Collapsible Compilation Error

Currently, I am working on a project that involves Spring and ReactJS. I am still new to front-end development. One of the tasks I am trying to accomplish is creating a simple accordion using "REACT-COLLAPSIBLE". The code I have written is quite straight ...