What is the best way to invoke server side code using JavaScript in ASP.NET?

I am working with a Repeater control in my project, and here is how it is set up:

<asp:Repeater ID="repeaterCategoryList" runat="server" 
                onitemcommand="repeaterCategoryList_ItemCommand">
                <ItemTemplate>
                        <td class="center">
                            <asp:Button ID="buttonDelete" runat="server" CssClass="btn btn-primary" CommandName="Delete" Text="Delete" 
                                CommandArgument='<%# Eval("CategoryId") %>'/>
                        </td>
                    </tr>
                </ItemTemplate>
            </asp:Repeater>

This is how I handle the delete command in my code-behind page:

protected void repeaterCategoryList_ItemCommand(object source, RepeaterCommandEventArgs e)
{
    if (e.CommandName == "Delete")
    {
         //perform server-side logic here
    }
}

Additionally, I have some javascript code in the .aspx file as well:

<script>
    $(function () {
        $('#buttonDelete').live('click', function (e) {
            e.preventDefault();
            $.alert({
                type: 'confirm'
                , title: 'Alert'
                , text: '<p>Are you sure, you want to delete this category</p>'
                , callback: function () {

                    // call server side logic from here
                }
            });
        });

    });
</script>

I am looking for a way to execute the delete command logic of the repeater using JavaScript. Is there an alternative approach to achieve this?

Answer №1

To bind a Javascript function to the Delete Button onclick event using the ItemDataBound property of a repeater, follow these steps:

CodeBehind:-

 void Repeater1_ItemDataBound(Object Sender, RepeaterItemEventArgs e)  
 {     
   if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) 
      {
        int IdToBeDeleted=((Label)e.Item.FindControl("idFieldControl")).Text;     
        Button Btn= (Button)e.Item.FindControl("buttonDelete");     
        Btn.Attributes.Add("onclick","return ConfirmDelete('"+IdToBeDeleted+"')");    
      }

 } 

Javascript:

<script>  
  function ConfirmDelete(var idVal) 
  {    
     if(Confirm("Are you sure you want to delete this item?")) 
      {
         var xmlhttp;
         if (window.XMLHttpRequest)
         {// code for IE7+, Firefox, Chrome, Opera, Safari
             xmlhttp=new XMLHttpRequest();
         }
         else
         {// code for IE6, IE5
             xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
         }


         xmlhttp.onreadystatechange=function()
         {
            if (xmlhttp.readyState==4 && xmlhttp.status==200)
               {
                 alert(xmlhttp.responseText);
               }
         }
          xmlhttp.open("POST","DeletePage.aspx?id="+idVal,true);  
          xmlhttp.Send();
      }
  } 
</script> 

DeletePage.aspx:

function pageLoad(sender, eventArgs) 
{ 
    if(!IsPostBack)
     {
       int IdToBeDeleted=Request.QueryString["id"];
       Write Your Delete Code Here...
       if delete successful...Response.Write("Delete Successful");
     }
} 

Answer №2

To control server-side method execution, you can utilize the OnClientClick attribute in a button's click event handler by specifying the function name within it. If the JavaScript function returns false, the server-side method will not be called. Conversely, if the JS function returns true, the server-side method will be executed.

<asp:Button ID="buttonDelete" runat="server" CssClass="btn btn-primary" CommandName="Delete" Text="Delete" onclick="Button_Click_Event" OnClientClick="return Javascript_Function()" CommandArgument='<%# Eval("CategoryId") %>'/>

Using OnClientClick is essential for controlling the interaction between a button and its post-back behavior.

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

What is the best way to adjust the size of the browser window when opening my page?

I have created a single page scrolling website specifically designed for children. The optimal viewing experience is at 1200 pixels wide. Is there a method to set the window size to that by default when visitors land on the site? ...

Resize the v-select component in Vuetify to make it more compact and easily fit within a paragraph

Currently, I am facing a dilemma where I have a paragraph that requires a select box to be placed right in the middle of it. However, the v-select component is too large and does not seem to offer any control over its width. This is how it currently appea ...

Error Message: TypeError - Unable to access property 'method' as it is not defined

I've just started working on a new node project and I've encountered an issue that I can't seem to figure out. :\Users\RTECH\Desktop\work\aumentedreality\modelViewerwithExpress\node_modules\express&b ...

JQuery Form Submission Failing to Trigger Controller Function

Attempting to submit a form in a JSP using JQuery/AJAX to call a method in a Spring Controller. The JSP structure is as follows: <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> < ...

A collection of jQuery objects that consist of various DOM elements as their properties

Seeking a more concise and potentially more streamlined approach using jQuery. I have an object called lbl which represents a div. Inside this div, there is a span tag that contains the properties firstName and lastName of the lbl object. Here's how t ...

Tips for utilizing onclick in React Threejs with a loaded GLTF model

After loading the GLTF file successfully and admiring its appearance, a desire arises to interact with it by clicking on it and extracting specific information, such as a uuid. However, upon attempting this interaction, an error is triggered stating "TypeE ...

Numerous JQuery AJAX form submissions leading to individual outcomes

I have implemented a script on my page that handles form submissions for multiple forms by calling a specific action. Here is the script: $(function () { $('form').submit(function () { if ($(this).valid()) { $.ajax({ ...

How to use jQuery to extract a particular text from an anchor tag

If I want to choose a specific anchor text and make changes to it, I can do so by targeting anchors with a certain href attribute. For example, on a page with multiple unordered lists, each containing different links: <ul> <li><a href="v ...

Initiate Sequential Batches of API Calls

In search of an efficient method to send approximately 1000+ requests in batches, such as 6 in parallel, and once these 6 have finished, move on to the next set Sending requests in batches will prevent the browser's request queue from getting complet ...

Play video on slick slider slide completion

Currently, I am utilizing slick slider to craft a hero block where both a Vimeo video and an image are set to automatically slide. The functionality is working as intended; however, I am looking to have the autoplay pause once the slide containing the Vime ...

The dropdown menu in Mantine is malfunctioning, even though I copied and pasted the exact code from

While following a tutorial, I encountered an issue with the Mantine Menu and Dropdown components. The tutorial creator did not wrap the React App inside the MantineProvider, which resulted in errors when trying to use the Dropdown component. Even after add ...

Customize the focus function for an individual element

I am working on a custom component that needs to seamlessly integrate with the native blur and focus functions. My goal is to override these functions in order to achieve the specific functionality I need. Currently, I have managed to override the prototy ...

Create an Angular 2 webpack production project and ensure that the dist folder does not contain any source code

I am currently developing a web application using Angular 2 with TypeScript and angular-cli. I needed to test the application on the server without uploading the source code, so I used the command "ng build --prod". Despite deleting all .map files from the ...

What is the best way to implement a loading cursor when the Submit button is clicked?

Is there a way to incorporate a progress cursor into my code in order to notify the user to wait when they click the Submit button or the Upload Button while uploading multiple files? Below is an example of my form: <form action="" method="post" enct ...

Creating a dynamic word cloud in D3: Learn how to automatically adjust font sizes to prevent overflow and scale words to fit any screen size

I am currently utilizing Jason Davies' d3-cloud.js to create my word cloud, you can view it here 1. I'm encountering an issue where the words run out of space when the initial window size is too small. To address this, I have a function that cal ...

Unable to fetch Title from Strapi

I have a collection type named posts with the following values: https://i.sstatic.net/49OeV.png To access the API, I have a file in my lib folder that contains the following code: export async function getPosts() { var api_base_url = process.env.API_BASE ...

Could there be a tag present in the DOM that is not visible on the page?

During my browsing session, I encountered a scenario in which I located an "anchor" tag within the DOM using xpath. However, the corresponding element was mysteriously missing from the page. To add to the confusion, when I tested the tag, the click() ope ...

Encountering issue in Angular 2 unit test: Error message states that 'subscribe' is not a property of undefined

I am currently focused on writing Jasmine unit tests for my Angular 2 application. it('ensure object passed to cancellation service is in correct format for cancel contract transaction', () => { var cancelReason = new models.CancelReason( ...

Error Checking in AngularJS Form Submission

According to my form.json file, I have a form that needs validation and a simulated submission. Firstly, I need to address this issue: fnPtr is not a function Next, I want to submit the form to a mocked API endpoint that will return true or false. Can I ...

Transferring callback variables from an Express GET request to a forked process in Node.js

I encountered an issue while trying to transfer the callback variables from app.get() to a forked process. The error message I received was: TypeError: Converting circular structure to JSON The primary goal behind this endeavor is to enable a main node w ...