The delete function in aspx.cs never seems to be triggered from the .aspx file

I am encountering an issue with deleting items from a list, as my delete function in the .aspx.cs file is not being called.

Below is my JavaScript code:

function doTheDelete(doIDeleteExpenses) {
        if (selectedExpensesList.length > 0) {
            $.ajax({
                type: "POST",
                url: '<%=ResolveUrl("~/Expenses/ViewExpenses.aspx/deleteSelectedExpense")%>',
                data: "{'DeleteExpenses' : " + "'" + doIDeleteExpenses + " '}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    var ss = data.d;
                    if (ss.length > 0) {
                        for (var i = 0; i < ss.length; ++i) {
                            $.noty.consumeAlert({ layout: 'center', type: 'error', dismissQueue: true });
                            alert(ss[i]);

                        }
                    }
                    $("#viewTasksGrid").flexReload();
                },
                error: function (data) {
                    $.noty.consumeAlert({ layout: 'center', type: 'error', dismissQueue: true, modal: true });
                    alert('Error Deleting Expense');
                    if (window.console) {
                        console.log(data);
                    }
                }
            });
        } else {
            showMessage('No expenses are selected.');
        }
    }

    function getSelectedExpenseIDs() {
        var selectedExpensesList = new Array;
        var i = 0;
        $('.expenseCheckBox:checked').each(function () {
            if ($(this)[0].id !== "checkAllExpenses") {
                selectedExpensesList[i] = $(this)[0].id.split('_')[1];
                ++i;
            }
        });
        return selectedExpensesList;
    }

Here is the method in the aspx.cs file that is not getting called:

[WebMethod]
public static string[] deleteSelectedExpense(bool DeleteExpenses, String[] ExpID)
{
    var rList = new List<string>();
    var canDeleteExpenses = false;
    var investigatorID = (int)HttpContext.Current.Session["InvestigatorID"];
    var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["OSCIDConnectionString"].ToString());
    var cmd = new SqlCommand("p_Admin_Permissions_CanDeleteExpenses", conn);

    // Code for handling database connection and deletion of expenses

    return rList.ToArray();
}

When inspecting the browser console, I receive an internal server error (500).

Answer №1

It appears that your parameters are incorrect for the deleteSelectedExpense method. This method is supposed to take both a boolean and an array of strings as parameters, but it seems like you are only passing the boolean value.

UPDATE: It seems like you might not be passing the string array correctly. In order to pass an array of string values in JSON format, it should look something like this: expId : [ 1, 2, 3 ]. This is why I am using the myArray.join method and adding brackets around the values.

var myArray = ['100', '200'];
$.ajax({
         type: 'POST',
         url: 'WebForm1.aspx/testMethod',
         contentType: 'application/json; charset=utf-8',
         dataType: 'json',
         data: '{ del: true, expId : [' + myArray.join(",") + '] }',
         success: success,
         error: error
       });
function success(data) {
    $('#result').html(data.d);
}
function error(data) {
    $('#result').html(data.d);
}

WebMethod:

[WebMethod]
public static string testMethod(bool del, string[] expId)
{
    var rand = new Random();
    return rand.Next().ToString();
}

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

HTML: Mark the chosen hyperlink or tag

In my HTML page, I am looking to keep the link selected when it is clicked on. Here is the initial HTML code: <table class="main-dev"> <tr> <td> <a class='titleForm' style="cursor:pointer"> ...

"Transforming a list retrieved from Django context into a JavaScript or Vue.js list: A step-by-step guide

Having a basic list presented in the django context. rlinks: ['test1', 'test2'', 'test3'] var v_root = new Vue({ delimiters: [ '[[', ']]' ], el: '#vue-main', data: { job ...

Adjust the height of the page to fit the available screen space on mobile devices

Seeking a solution to ensure my web app fills the entire height of the device. Currently utilizing 100vh on the body tag, however, Safari tab on iOS adds an additional height which causes users to have to scroll down to view the full page. Any suggestions ...

Which specific element of CSS should be adjusted to ensure compatibility with Internet Explorer?

Struggling with my one-page website layout, I made some adjustments to have six sections in the HTML. Everything seemed to work fine on all browsers except for Internet Explorer. It kept redirecting me to a weird spot between the second last and last two s ...

Error in Angular Due to Circular Reference in JSON

I'm currently working on integrating a tree structure in AngularJS. The goal is to construct the tree by dynamically adding nodes based on user input from an Angular Select element. Here is the specific operation I'm trying to accomplish: var a ...

Strategies for consolidating functions from the default.aspx.vb page into a separate class

This question pertains to structure : Currently, I have a Default.aspx page that contains references to (XML) services and handles the innerHTML of HTML objects. The number of buttons displayed is determined by the output of these services. Given the com ...

Verify the dimensions of the window, either width or height

Is there a way to create a condition that checks for window size based on width and height individually? Currently, using '&&' only checks if both width and height are low. How can this condition be modified to display a message if the width is a ...

Issues have been identified with the performance of Ionic Material List when used in conjunction with ng

In my project involving the Ionic floating menu button, everything is working fine. However, I have encountered an issue where when I click on the + button, I do not want to be able to click on the click me button while the menu is open (Req1.png)https://i ...

Verifying website responsiveness using Puppeteer

Looking to create a script that can determine if a webpage has a responsive design? Wondering how to go about it? Well, it's quite simple. In responsive websites, elements like divs, spans, footers, headers, and sections typically adjust to fit the s ...

Apply a style to the div element that contains a TextInput component

As a beginner in the world of React and Material UI, I am currently working with Material UI version "1.0.0-beta.17", React 15.6.2, styled-components 2.0.0, and styled-components-breakpoint 1.0.1. Within a div element, I have two TextInput fields. const ...

React Native displaying identical path

Is there a way to dynamically change routes in React Native when a button is pressed? Inside my SplashContainer component, I have the following method: handleToSignUp = () => { console.log("Running handleToSignUp") this.props.navigator.push({ ...

Guide for executing Java code and displaying HTML form fields concurrently in JSP

I have created a JSP page with form fields and Java code in scriptlets. I have imported the Java code into the JSP page and created an object to call the functions of that Java class. When I run the JSP, the page remains blank until all the Java code has ...

Implementing React router for dynamic page rendering

I'm struggling to make sense of a particular piece of code. Can someone provide an explanation? I'm particularly confused about the role of "props" in this section and how it is essential for the code to work correctly. If I remove "props," my co ...

What are the counterparts of HasValue and .Value in TypeScript?

There is a method in my code: public cancelOperation(OperationId: string): Promise<void> { // some calls } I retrieve OperationId from another function: let operationId = GetOperationId() {} which returns a nullable OperationId, operat ...

Is it possible to customize the default styling options in Tailwind?

I am currently working on a blog using NextJS, and I have encountered an issue with Tailwind's list style type. It seems that the default styling for list style type is set to list-none, resulting in my <ul> <li> elements not being styled ...

Break apart the values of a Bootstrap multiselect into separate variables

Can you please assist me? I am trying to extract separate values from a multi-select field. var branch=$('#branch').value; //branch = 101,102,103; I need these values to be separated like this: id='101' or id='102'... My g ...

Creating a Precise Millisecond Countdown Timer using Angular 4 in Javascript

I'm currently facing a challenge in Angular 4 as I attempt to develop a countdown timer that accurately displays milliseconds once the timer falls below 1 minute (59 seconds or less) for a sporting event clock. My issue lies with the setInterval funct ...

Tips for effectively utilizing ReactJS and the useState hook for rendering data accurately

I've encountered a problem that I'm struggling to solve. Within my database, there exists a table of orders: Table stored in the database id - Order identification number items - Collection of product objects transaction_date - Date of transact ...

Is the HTML5 capture attribute compatible with wkwebview?

Is it supported as stated in the title? For more information, you can check out the MDN documentation (Incomplete) and the Caniuse list of supported browsers. Surprisingly, none of them mention wkwebview. Does this attribute have support in wkwebview? Kno ...

What are some simple techniques for displaying JSON data in a text box on a webpage?

I'm currently utilizing edit_area_full.js on several of my web pages to format python code snippets. However, I have encountered situations where I need to display formatted JSON data, which edit_area does not support. Can anyone recommend a suitable ...