Executing a backend C# function from a front end Javascript function in ASP.NET: A Step-by-Step Guide

As part of my current unpaid internship in C# and Asp.net, my employer has assigned me the task of implementing a JavaScript function to prompt the user for confirmation before deleting a record from the database.

After conducting thorough research, I successfully wrote the JavaScript function that notifies users about their intention to delete a particular record before proceeding with the action.

While the JavaScript function functions correctly, I now face the challenge of invoking the backend C# function responsible for actually removing the record from the database using the front-end JavaScript function I just developed.

Below is the code:

Javascript function:

function watchdelete() 
{
    if (confirm("Are you Sure You want to delete this Manufacturer?") == true)
   {
        __doPostBack('btnDelete_Click','');//"PageMethods.btnDelete_Click();
   }
    else { }
}

The frontend section which triggers the client-side JavaScript code attached to the delete button:

<asp:Button ID="btnDelete" runat="server" Text="Delete" OnClientClick=" return watchdelete()" OnClick="btnDelete_Click1" />

The backend C# function that needs to be called to delete the record from the database:

protected void btnDelete_Click(object sender, EventArgs e)
{
    // Code simplified for clarity
}

Any suggestions or insights on how to tackle this issue would be highly appreciated. Thank you.

Answer №1

To simplify your validation function, you can use the following code:

function confirmDelete(){
  return confirm("Are you sure you want to delete this Manufacturer?");
}

After simplifying the function, your button with the OnClientClick attribute will look like this:

OnClientClick="return confirmDelete()"  

If the validation function returns false, .NET will prevent your code from being submitted to the server.

Answer №2

To explain how to trigger backend functions from client-side Javascript, I'll simplify it in my own words: Step 1. Write your Javascript function and place it on the client side, making sure scripts are enabled. Here's an example code snippet:

   <script type = "text/javascript" >
    function confirmDelete() {
        return confirm("Are you Sure You want to delete this Manufacturer?");
    }
  1. Create your button or control front-end code with OnClientClick set to the name of your Javascript function preceded by 'return'. See example ASP code in the original post.

  2. Activate the backend C# function as usual, such as double-clicking on the button in Visual Studio design view to generate the backend function in the code behind page. Code the backend function as needed.

  3. Once step 3 is completed correctly, your OnClick should match your backend C# function.

  4. Test your application. If your front-end javascript returns true, it should trigger the backend function automatically if a return statement is included in the front-end code as shown in the original post.

Sometimes simplicity is the key - it's all up to you.

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

Sending a text parameter to the JavaScript Executor within a Selenium framework

Although this question has been asked before, I have searched for multiple answers and have not found a solution to my specific problem. if (driver instanceof JavascriptExecutor) { System.out.println("In try"); ((JavascriptExecutor)driver) ...

Discord.js: AbortError: The request was cancelled by the user

Recently, while working on my ticket system and the process for logging transcripts, I encountered an unexpected error that caused transcripts to fail sending. This issue never occurred before. The error message displayed was: [Error Handling System] Multi ...

How to identify the character encoding in a node.js request

Did you know that Facebook chat has a feature where it automatically detects and displays messages in a left-to-right format when typing in English, but switches to right-to-left style when adding right-to-left characters? I'm curious about how Faceb ...

What is the best way to sort a table by column index using HTML?

I find myself in a situation where I am not well-versed in HTML, Javascript, and CSS. Here is the scenario: <div class="table"> <table class="display-table"> <thead> <tr> ...

What causes socket to read 0 bytes even though more data was accessible

I encountered a situation where the following code was causing a loop with 100% CPU usage: byte[] buffer = new byte[0x10000]; while (true) { if (socket.Poll(5000000, SelectMode.SelectRead) == false) continue; int available = socket.Availab ...

Generating directory for application, only to find TypeScript files instead of JavaScript

While following a tutorial on setting up a react.js + tailwindcss app, I used the command npx create-next-app -e with-tailwindcss [app name]. However, instead of getting javascript files like index.js, I ended up with TypeScript files like index.tsx. You c ...

Comparing the name and URL of a link using Selenium webdriver in C#

I am currently looking for ways to automate the testing of links on a Sharepoint site, ensuring they are connected to the correct URL. However, I have hit a roadblock when it comes to performing the comparison. After locating the links and adding them to ...

Does anyone have any sample code on processing JSON data from a URL using Modified JavaScript Value in Java?

Could anyone provide some examples on how to handle returned Json data using Modified JavaScript Value? Here is the specific data I require from the json url: { "result": { "data": [ { "name": "page1", "period": "dia", "values": [ { "value": 4, "end_time" ...

While typing, React-hook-form is removing the input field when the mode property is enabled

Currently, I am implementing a basic form using react-hook-form version 7 along with Material UI. However, I have encountered an unusual behavior when configuring the mode in useForm({mode: ".."}). Below is a snippet of my code: import { yupResol ...

What is the best method for choosing visible elements within a scrollable container?

Is there a way to retrieve the list of visible elements within a scrollable container? The number of elements that are visible on the screen changes as one scrolls, making it challenging to add a specific class to only the last two visible elements. Any s ...

Trying out a React component that relies on parameters for connection

Having an issue while attempting to test a connected react component that requires a props.params.id in order to call action creators. During the testing process, when checking if the component is connected to the store, an error "Uncaught TypeError: Canno ...

Perform a MongoDB find() query using the _id field as the search criteria

So I am currently working on my express app and I need to find data based on the _id field in MongoDB. Below is a snippet of my MongoDB record: { "_id": { "$oid": "58c2a5bdf36d281631b3714a" }, "title": "EntertheBadJah" ...

Having trouble importing a module in my Node.js/Express application

I've encountered an issue while trying to import files into my node js server file. My usual method is correct in terms of paths, so I'm puzzled about what the error might be. import express from 'express' import mongoose from 'mon ...

JavaScript featuring Ajax functionality

Although I have limited experience in web programming, I am currently testing a simple add-on to integrate with my app. The webpage I have created displays multiple rows, each containing an editable field for user input. After the user inputs data into th ...

Creating dynamic form fields using AngularJS

I have a form that includes an input field, a checkbox, and two buttons - one for adding a new field and one for deleting a field. I want to remove the add button and instead show the next field when the checkbox is checked. How can I achieve this? angu ...

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. https://i.sstatic.net/PG1Ha.png The desired structure should resemble the one shown in this image. I have made modificatio ...

Checking the authenticity of Javascript Objects containing date values

What is the best way to validate a JavaScript Object that includes date fields? While there are JSON validators such as tv4 that can check the format of string dates, our business logic operates with JavaScript Date instances which these validators do not ...

A customized Javascript application designed specifically for Blackberry Bold users, enabling them to effortlessly choose a country and seamlessly enter a correctly formatted zip code in the designated text field

I am currently developing a mobile web app for Blackberry Bold 9700 & 9650 devices running on the 5.0 browser. The main functionality of the app involves allowing users to select either US or Canada from a drop-down menu. Based on their selection, the ...

Enhance Your Browsing Experience with Ajax Chrome Extension

I tried sending the URL to a PHP file in a Chrome extension, but I'm having trouble getting a response. manifest.json { "name": "Get pages source", "version": "1.0", "manifest_version": 2, "description": "Get pages source from a popup", "b ...

Using JavaScript to launch a new window for a specific folder

When opening a popup window with a specific URL, I typically use the following code: $("#OpenFolder").click(function () { var url = "https://stackoverflow.com"; windowObjectReference = window.open(url, "ModulesList", " ...