Utilizing ASP.NET MVC Kendo Grid to invoke a controller method via JavaScript

To implement a custom modal confirmation popup, I need to invoke the method .Destroy("Remove", "Attachment") from javascript. How can I trigger the Remove method in javascript? I have identified where I would like to make this call in the code snippet. Additionally, how do I pass the OrderViewModel through?

Below is my grid setup:

@(Html.Kendo().Grid<TelerikAspNetCoreApp7.Models.OrderViewModel>()
        .Name("grid")
        .Columns(columns =>
        {
            columns.Bound(p => p.OrderID).Filterable(false);
            columns.Bound(p => p.Freight);
            columns.Bound(p => p.OrderDate).Format("{0:MM/dd/yyyy}");
            columns.Bound(p => p.ShipName);
            columns.Bound(p => p.ShipCity);
            columns.Command(command =>
            {
                command.Custom("Destroy")
                    .Click("showDeleteConfirmation")
                    .HtmlAttributes(new { style = "width:40%" });
            }).Width("15%");
        })
        .Pageable()
        .Sortable()
        .Scrollable()
        .Filterable()
        .HtmlAttributes(new { style = "height:550px;" })
        .DataSource(dataSource => dataSource
            .Ajax()
            .PageSize(20)
            .Destroy("Remove", "Attachment")
            .Read(read => read.Action("Orders_Read", "Grid"))
            .Destroy(read => read.Action("Orders_Read", "Grid"))
        )
)

Here is the modal dialog setup:

@(Html.Kendo()
        .Dialog()
        .Name("DeleteConfirmation")
        .Modal(true)
        .Title("Confirm Delete")
        .Content("Are you sure you want to delete this item?")
        .Visible(false)
        .Actions(a =>
        {
            a.Add().Text("No").Action("cancelDelete");
            a.Add().Text("Yes").Action("confirmDelete").Primary(true);
        })
)

The required scripts are as follows:

<script>
    var modelToDelete;

    function showDeleteConfirmation(e) {
        e.preventDefault();
        var grid = $("#grid").data("kendoGrid");
        var dialog = $('#DeleteConfirmation').data("kendoDialog");

        modelToDelete = grid.dataItem($(e.target).parents('tr'));
        dialog.content("Are you sure you want to delete this item with ID - " + modelToDelete.OrderID + "?");
        dialog.open();
    }

    function confirmDelete(e) {
        //how to call .Destroy("Remove", "Attachment") from here
    }

    function cancelDelete() {
    }
</script>

The controller action for removing an attachment:

public ActionResult Remove([DataSourceRequest] DataSourceRequest request, OrderViewModel attachmentVm)
{
    Attachment attachment = _db.Attachments.FirstOrDefault(o => o.Guid == attachmentVm.Guid);
    attachment.IsActive = false;
    attachment.LastUpdated = DateTime.Now;
    attachment.LastUpdatedBy = _sessionUser.Username;
    _db.SaveChanges();

    return Json(ModelState.ToDataSourceResult());
}

Answer №1

Below is the provided solution:

function confirmDeleteAttach(e) {
    $.ajax({
        url: '/Attachment/Remove',
        data: { Guid: modelToDeleteAttach.Guid },
        type: "POST",
        success: function () {
            gridToDeleteAttach.dataSource.remove(modelToDeleteAttach);
            $('#DeleteConfirmationAttach').data("kendoDialog").close();
        }
    });
}

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

Angular2's hidden feature isn't functioning properly

There is a common suggestion to use *ngIf better than [hidden] but in my scenario, I want to keep the element in the DOM without it being visible. In my component.html file, I have: <article #articleId id="bodyArticle" [hidden]="isClicked"></art ...

v-for based on element type

I'm facing an issue with a basic vue.js application. I have a list of referees and I need to iterate through that list and add data from an ajax request to each item. Strangely, when I try to display the list using v-for on a span element, it works pe ...

How can the ID of a table row be retrieved if it is selected?

In my datatable, I have a list of Cars where each row contains a Car ID. A checkbox column has been added to the first cell in the table - when checked, the row is highlighted to show the user their selection. The goal is to retrieve the IDs of all selecte ...

Why won't my div tag show conditionally with AngularJS ng-show?

I'm having trouble displaying a div tag on a form based on the boolean flag specified in ng-show. Unfortunately, the div is not showing up at all. Here's what I've tried so far without success. Any assistance would be greatly appreciated! F ...

Scrollable container with jQuery draggable functionality

I am currently working on implementing a draggable list that I want to contain within a scrollable div. $( ".draggable" ).draggable(); Here is the fiddle I have created for this: http://jsfiddle.net/YvJhE/660/ However, the issue I am facing is that the ...

Auto-complete feature not populating the input field in Google Chrome

Within my register form, I have various INPUT tags present. One of these INPUTs has the name email. <input type=text name=email id=email> When filling out this form in Chrome, I encounter a peculiar behavior. Upon clicking on the email input field ...

Step-by-step guide for implementing an "on change" event for a select box within a dialog box

I recently wrote an HTML code snippet like this: <div id = "dialog-1" title = "Dialog Title goes here..."> <select id= "lang" name= "lang"> <option value="1"> TEXT </option> <option value="2"> HTML </op ...

What is the best way to apply CSS styles to a child div element in Next.js?

I'm currently working on enhancing the menu bar for a website project. Utilizing nextjs for my application I am aiming to customize the look of the anchor tag, however, encountering some issues with it not rendering correctly. Here is a snippet of ...

Troubleshooting Vue Single File Components Displaying Missing Styles

I'm currently attempting to incorporate styles into a vuejs single file component. I've successfully achieved this in a node app previously, but now I am working with a python/flask backend (not that it should make a difference). The Vue componen ...

Using jest.fn() to simulate fetch calls in React

Can anyone explain why I have to include fetch mock logic within my test in order for it to function properly? Let's take a look at a simple example: Component that uses fetch inside useEffect and updates state after receiving a response: // Test.js ...

"Exploring the Differences between JavaScript, AJAX, and Servlet for String

I am attempting to compare a string that is received from a servlet. The servlet page returns the following: out.println("pass"); In JavaScript: function Check() { if (ajax.responseText === "pass") { document.getElementById("pass").innerHTML = "This is ...

Tips for setting a value from an AJAX-created element into a concealed form field

There is a div that contains a button. When the button is clicked, a form appears. The div's id is then assigned to a hidden field within the form. This functionality works for the divs that are present on the page when it initially loads, but it does ...

Leveraging Angular to dynamically adjust the height of ng-if child elements based on parent

I'm struggling with a few things in my current setup. I have a view that consists of 3 states - intro, loading, and completed. My goal is to create a sliding animation from left to right as the user moves through these states. Here is the basic struc ...

Node.js SQLite3 - DB.each() not running the subsequent code block

When running the code snippet below, I am getting the following output: var db = new sqlite3.Database("database.sqlite") console.log("2") db.each("SELECT * FROM gban WHERE id = '"+id+"'", async functi ...

What sets class/instance methods apart from static methods when it comes to their functionality in applications?

As I develop APIs for my application, I've been curious about the difference between defining functionality methods like this: class Foo { static method1(req, res) {} static method2(req, res) {} } and class Foo { method1(req, res) {} method ...

What is the best method to retrieve a secure httponly cookie in a Next.js application?

Our next JS application is making a request to The backend team has configured the response cookie as a secure HttpOnly cookie. const session = await ( await fetch( `https://demo.com/auth/session`, requestOptions )).json(); console.log(&qu ...

How to Assign a Specific ID to the Body Tag in Wordpress Using functions.php

Struggling to find a simple solution after scouring the web for answers. Most tutorials are overly complicated. I'm attempting to integrate a jQuery menu system into my Wordpress site and want to assign a unique body ID to make targeting easier. I p ...

form controls disappear upon adding form tags

Currently experiencing an issue with angular and forms that I could use some help with. I have a dynamic form that is functioning properly, but now I need to add validations to it. After following this guide, I established the structure correctly. Howeve ...

In order to have the bot repeat a structure for every user, I would need to utilize both mongoose and discord.js

I am utilizing MongoDB (mongoose) to establish a database for storing user notes in my Discord bot, which is being developed with Discord.JS. This is my "Guild.js" file: const { Schema, model } = require('mongoose'); const Guild = Schema({ i ...

Implementing a Vue.js v-bind:style attribute onto a dynamically generated element post-page initialization

Let me start by explaining my current issue and dilemma: I have been tasked with converting an existing JS project into a Vue.js framework. While I could easily solve a particular problem using jQuery, it seems to be posing quite a challenge when it comes ...