Remove data from a database using Ajax in ASP.NET MVC without utilizing DataTables

I'm encountering a slight issue with my code. I am attempting to delete a row from the database without using DataTables in ASP.NET MVC, but it seems to be not working as expected. I have displayed all items from the database on a page within div elements. Here is a snippet of how it looks:

Index:

Default Edit/Delete buttons

<input type="button" value="Edit" class="btn btn-warning btn-sm mt-auto" onclick="location.href='@Url.Action("Edit", "Products", new { id = item.Id })'" />
<input type="button" value="Delete" class="btn btn-danger btn-sm mt-auto" onclick="location.href='@Url.Action("Delete", "Products", new { id = item.Id })'" />

Using the default button requires going to the Delete View and pressing Delete again, which I want to avoid. That's why I chose to implement Bootbox with Ajax

Therefore, I removed the Delete button and added this instead:

<button data-product-id="@item.Id" class="btn btn-danger btn-sm mt-auto js-delete">Delete</button>

This is my controller:

// GET: Products/Delete/5
    public ActionResult Delete(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Product product = db.Products.Find(id);
        if (product == null)
        {
            return HttpNotFound();
        }
        return View(product);
    }

    // POST: Products/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        Product product = db.Products.Find(id);
        db.Products.Remove(product);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

And here is the script that I am using:

$(document).ready(function () {
    $(".products-panel .js-delete").on("click", function () {
        var button = $(this);
        bootbox.confirm("Do you want to delete this product", function (result) {
            if (result) {
                $.ajax({
                    url: "/Products/Delete/" + button.attr("data-product-id"),
                    method: "GET",
                    success: function () {
                        $(button).parent().parent().remove();
                    },
                    error: function (err) {
                        console.log(err);
                    }
                });
            }
        });
    });
});

Currently, it only removes the div element of that item until the page is refreshed. It does not remove it from the database. Is there any way to fix this?

If more photos are needed, I am happy to provide them.

Answer №1

The issue has been resolved by removing the GET Delete action from the Controller and renaming the Post method from DeleteConfirmed to Delete

Before:

// GET: Products/Delete/5
public ActionResult Delete(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Product product = db.Products.Find(id);
    if (product == null)
    {
        return HttpNotFound();
    }
    return View(product);
}

// POST: Products/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
    Product product = db.Products.Find(id);
    db.Products.Remove(product);
    db.SaveChanges();
    return RedirectToAction("Index");
}

Updated:

    // POST: Products/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult Delete(int id)
    {
        Product product = db.Products.Find(id);
        db.Products.Remove(product);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

A big thank you to everyone who offered their assistance

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

Transferring information to a controller using ajax in ASP.NET Core

I am encountering an issue with sending data to the controller through ajax. The value goes as "null". Can someone please assist me with this? Here are my HTML codes: <div class="modal fade" id="sagTikMenuKategoriGuncelleModal" data ...

Attempting to utilize the LLL algorithm as described on Wikipedia has led to encountering significant challenges

I'm struggling with determining whether my issue stems from programming or understanding the LLL algorithm mentioned on Wikipedia. To gain a better understanding of the LLL algorithm, I attempted to implement it following the instructions outlined on ...

Building a custom Vuetify extension to enhance core features

I am currently working on developing a plugin-based component library to ensure consistency across various product lines using vuetify. However, when I try to install the library and add the components, I encounter multiple errors related to the dark theme ...

Tips for fixing the issue "Uncaught SyntaxError: Unexpected token S in JSON at position 0"

After referencing sols of SO, I am still unable to solve the error. I have a file dashboard.html which contains search conditions. When clicked, it calls loadtable.js. This loadtable.js file uses search.php to retrieve rows from a table. However, encount ...

"Enhance Your Drupal 7 Profile with a Dynamic Ajax Upload Button for Profile

How can I implement an AJAX "upload" button next to the file input in Drupal 7 Profile Picture? When clicked, the selected image should be uploaded. ...

Encountering a Hydration Error with Next.JS and MDX-Bundler when a MDX Component Adds Extra New Lines to its Children

Currently, I am incorporating next.js + mdx-bundler into my project. There is a simple component that I frequently use in my mdx files. Everything runs smoothly with the following code: Mdx is a great <Component>format and I like it a lot</Compon ...

Add up the duplicate elements in two arrays

I have dynamically created two arrays with the same number of cells (where array.length is the same, representing a key and value association). Below are the arrays: barData.labels["Food", "Food", "Food", "Food", "Food", "Food", "Food", "Food", "Food", "F ...

Do these exports serve the same purpose?

Can someone help me understand why one export works while the other doesn't? I've tried to figure it out on my own but I'm stuck. Functioning Example const dataStore = new Vapi({ baseURL: 'http://domain.test/api', state: ...

how to properly position an image using javascript

I have two tilesheet images and I have successfully rendered them, but I am struggling to figure out how to place the character in front of the map. https://i.stack.imgur.com/n1a3Q.png I have placed these images in two different JavaScript files. This i ...

Identifying a failed Ajax Request in JavaScript

How can I check if an Ajax request failed to load a file? Here is the code I'm currently using: var pro = undefined; var xmlhttp; if (window.XMLHttpRequest){ xmlhttp = new XMLHttpRequest(); } else{ xmlhttp=new ActiveXObject("Microsoft.XMLHTT ...

How can you obtain values from a nested JSON object and combine them together?

I have a javascript object that is structured in the following format. My goal is to combine the Name and Status values for each block and then store them in an array. { "datatype": "local", "data": [ { "Name": "John", ...

Is it better to store CSS and JavaScript in separate files or within the main HTML document

While the best practice is to place JavaScript and CSS code in separate files (such as .js and .css), many popular websites like Amazon, Facebook, etc. often include a large portion of their JavaScript and CSS code directly within the main HTML page. Whic ...

Dates comparison causing Firestore security rules issue

After running the query shown below, I encountered a permission-denied message with an error in the "Monitor rules" tab. const timeNow = useMemo(() => Timestamp.now(), []); const query = query( postRef, where("tags", "array-contai ...

Retrieving parameters from the URL in Angular

I'm facing an issue with my app. I am currently using a factory to manage data for two controllers. When I click on a link that redirects me to another view with a specific URL, I want to reuse the last tag in the URL by slicing it like this: window. ...

Utilizing jQuery boilerplate to execute functions

I am currently utilizing jQuery Boilerplate from However, I have encountered an issue where I am unable to call the "openOverlay" function within the "clickEvents" function. Oddly enough, I am able to successfully call "openOverlay" within the "init" fun ...

You cannot convert a function to a string while utilizing axios get in nuxtServerInit

While attempting to connect my app to the backend using Udemy's Nuxt.js course, I encountered a GET http://localhost:3000/ 500 (Internal Server Error) on the client side with the following code: import Vuex from 'vuex'; import axios from &a ...

Passing the title of a page as data to a component in Next.js

I am currently working on setting a custom title for each page within my next.js project. Here is an example of a simple Layout: const MainLayout = props => { return ( <Layout style={{ minHeight: "100vh" }}> <Head> < ...

Unable to integrate an if/else statement into the JSON reply

Working with an API to retrieve data and display images from it. I am attempting to implement an if/else statement that will show photos if the search term yields results in the response, and display a message indicating no results if it does not. Curren ...

Creating animations for freshly added content on the DOM

In the development of a web application, I am focusing on the front end aspect. My approach involves creating content based on JSON objects received from the back end. This content is then encapsulated in HTML and added to the DOM using jQuery's appen ...

What is the best way to correctly render several React components using a single index.js file?

I am facing an issue with rendering two React component classes. One class creates a counter and works fine, while the other class generates a simple string wrapped in HTML tags but does not render. I have tried various tutorials to troubleshoot this probl ...