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

Updates to object properties are not appearing in Vue component

I am facing an issue with a Vue component that has a single prop, which is an object. Despite changing a property in this object, it does not reflect the update in the Vue template. Below is a simplified version of the component: <template> <p ...

Can Node.js fetch a PHP file using AJAX?

The Challenge: Greetings, I am facing an issue with my website that features a game created using node.js, gulp, and socket.io. The problem arises when I attempt to call a php file from node.js. While the file returns a success message (echo in the file) ...

The error code TS2554 is triggered when 5 arguments are passed instead of the expected 3-4

I'm utilizing the gsap plugin to craft a captivating text animation effect. As I reached the last line of code in my 'animation_text_1' function, specifically where it states "TweenMax.staggerFromTo(.....)", an error cropped up which read: ...

Click event not triggering for selected option in jQuery dropdown menu

After adding dropdown anchor tags dynamically to the drop-down menu, the click event does not seem to be firing. Do I need to re-bind the click handler after using .append, or should I wrap the click handler in a function? <script src="https://code.jqu ...

Can dynamic loading JavaScript be debugged using a debugger such as WebKit, FireBug, or the Developer Tool in IE8?

After asking a question on Stack Overflow, I have successfully written JavaScript functions for loading partial views dynamically. However, debugging this dynamic loading script has been a challenge for me due to all loaded JavaScript being evaluated by th ...

How can I display base64 image data in a new window without triggering a block?

Currently experiencing challenges with Javascript. Utilizing html2canvas to convert a div to a canvas and then using .toDataURL to convert the canvas to a base64 data stream. Attempting to open base64 image data in a new window, but facing blocks from va ...

Problems with Nested Loops in JavaScript

I have a nested loop structure that looks like this: var len = bolumlerUnique.length; function sendSections() { for (i = 0; i < bolumlerUnique.length; i++) { elementSections = $("[sectionid=" + bolumlerUnique[i] + "]:checked"); cons ...

The React component does not trigger a re-render

Using React Redux, I am able to pass values successfully. However, the component I intend to render only does so once. Interestingly, when I save my code in VSCode, it renders again and the data displays on the page as expected. return ( <div classN ...

Total aggregate for a variety of Sliders (Bootstrap 4 & jQuery)

I am currently working on a web page that involves implementing 3 sliders. The total of all three sliders should always be limited to 100%. This project utilizes the Bootstrap 4 framework and jQuery 3.6.2 Here are my current challenges: The combined valu ...

Inverting the hierarchy of a tree structure

I am currently working with a tree structure and utilizing the jstree jQuery plugin. My main objective is to reverse the structure. The desired structure should resemble the one shown in this image. I have made modifications using MS Word, so it does not ...

Illumination causes surfaces to transform

In my simple scene, I have a ground and an interesting light source. However, when the light hits certain meshes, it creates some strange effects. The shadows are being cast correctly, but the other meshes affected by the light are showing unusual results. ...

Having trouble accessing a PDF file using gview

Having trouble opening a document I am unable to preview the documents and I'm not sure what I'm missing. I have read through various StackOverflow questions and answers related to this issue, but still no luck. url = http://192.168.0.6:8077/ ...

Ways to switch up the titles on UploadThing

Recently, I started working with the UploadThing library and encountered a situation where I needed to personalize some names within the code. Here is what I have so far: Below is the snippet of code that I am currently using: "use client"; imp ...

What makes Next.js API so special?

As I delve into Next.js, I find myself grappling with the concept of server-side rendering (SSR) and API usage. When is it appropriate to utilize the API folder within pages versus deploying my own server along with a database? Would there be any conflic ...

Safari has no issues running Javascript, but other browsers are encountering failures

I am facing an issue where the code is working on Safari but failing on other browsers, and I can't figure out why. You can find the html part and the main javascript part. The main issue at hand is: When executing the function downloadurl(url, fun ...

Does Node Express call the next middleware immediately when the next function is called?

Can someone please help me grasp the concept of how the next function operates within the Node Express framework? I know that we utilize the next function within the current middleware to trigger the execution of the subsequent middleware listed. These mid ...

Importing JavaScript files to work with Vue-Router: A Step-by-Step Guide

Seeking guidance on importing JavaScript files correctly throughout my Vue project, including within the components used to implement changes with Vue-Router. Currently, encountering an issue where I must reload the component in order for the JavaScript to ...

Tips on including starting information into an angularjs application from the displayed HTML

I'm currently working on a complex AngularJs application that requires User Login. Once the user is authenticated, a page will be displayed to them and additional data will be loaded later. There are two methods for achieving this: XHR Fetch af ...

Create a PDF document using a combination of charts and tables

When I try to create a PDF file with both the chart and table embedded, only the table is showing up. Can someone please provide me with some suggestions on how to resolve this issue? JSFIDDLE LINK ...

Unable to retrieve data from AJAX request in the AJAX success function

I've seen this question asked multiple times and I've gone through several answers regarding callbacks, but I'm still struggling to understand how to apply it to my specific situation. I have an ajax function that is being called from the su ...