Combining the Powers of JavaScript and ASP.NET

Describing the ASP.NET GridView control:

<asp:GridView ID="gvReq" runat="server" AllowSorting="True" DataKeyNames="Req_ID,Approved,supervisor_login,Revised,Requested_Login,HasDocs" DataSourceID="objdsReq" AllowPaging="True" PageSize="30" >

Within this GridView, there is a template field defined as follows:

<asp:TemplateField>
  <ItemStyle HorizontalAlign="Center" Width="50px"></ItemStyle>
  <ItemTemplate>
    <asp:Button ID="btnDelete" runat="server" CommandArgument='<%# Container.DataItemIndex %>' ForeColor="Red" CommandName="DeleteReq" OnClientClick="showConfirm(this); return false;" Text="Delete" />
  </ItemTemplate>
  <ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>

The JavaScript function for

OnClientClick="showConfirm(this); return false;"
can be found below. This was adapted from a post discussing similar functionality.

<script type="text/javascript">
  var _source; // tracks the delete button for the row to be removed
  var _popup; // keeps track of the popup div
  function showConfirm(source) {
    this._source = source;
    this._popup = $find('mdlPopup');
    this._popup.show();    
  }
  function okClick() {
    this._popup.hide();   
    __doPostBack(this._source.name, ''); 
  }
  function cancelClick() {
    this._popup.hide(); 
    this._source = null; 
    this._popup = null;
  }
</script>

To enhance the confirmation dialog, additional HTML tags were added to display more information:

<div id="popupDiv" runat="server" align="center" class="confirm" style="display: none">
  <img align="absmiddle" src="Images/important.png" /><b>CONFIRM:</b> Delete this item?<br />
  <asp:Button ID="btnOk" runat="server" Text="Yes" Width="50px" />
  <asp:Button ID="btnNo" runat="server" Text="No" Width="50px" />
</div>
<ajaxToolkit:ModalPopupExtender BehaviorID="mdlPopup" runat="server" TargetControlID="popupDiv" PopupControlID="popupDiv" OkControlID="btnOk" OnOkScript="okClick();" CancelControlID="btnNo" OnCancelScript="cancelClick();" BackgroundCssClass="modalBackground" />

Despite having the basic functionality in place, it became evident that the confirmation dialog lacked specificity.

Upon inadvertently deleting the wrong entry due to lack of clear identification,

I proceeded with the deletion action and observed my mistake after reviewing the code execution.

Seeking an improved solution led me to an article on c#, asp.net, and javascript interaction:

ASP.NET binding c #: 
<% # Bind ("column name")%> 
<% # Eval ("column name")%> 

The <a href/> binding c #: 
<A href = '<% # Eval ("column name ... aspx? Key = value & key = {0}")%>' /> 

The OnClientClick embedded js function (c # parameter is not passed): 
OnClientClick = "js function (parameter)" 

The OnClientClick embedded js function (pass a c # parameters): 
The OnClientClick = '<% # Eval ("column name", "js function ({0})")%>'> 
The OnClientClick = '<% # Eval ("column name", "javascript: js function (\" {0} \ ")")%>'> 

The OnClientClick embedded js function (passing two or more c # parameters): 
OnClientClick = '<% # String.Format ("js function ({0}, {1}", Eval ("column name"), Eval ("column name"))%>' 

c # embedded js function: 
Response.Write ("<script> js built-in function ('parameter') </ script>"); 
Page.ClientScript.RegisterStartupScript (this.GetType (), "", "js-defined functions ('parameter')", true); 

js call back method: 
var result = "<% = method name (shape parameter)%>"; 
public method type the name of the method (parameter) {..}

(Included here as a precaution)

Hence, the next step involved passing specific data to the Confirmation Dialog Box, such as the row's unique ID.

Requesting guidance on enhancing the code for passing additional data to the Confirmation Dialog Box using the existing structure.

Should the necessary information be extracted and transmitted to the Dialog Box, or can the JavaScript leverage the source parameter to access the required data?

Within the GridView control:

<asp:BoundField DataField="Req_ID" HeaderText="ID" SortExpression="Req_ID" />
<asp:BoundField DataField="Vendor_ID" HeaderText="Ven ID" SortExpression="Vendor_ID" />
<asp:BoundField DataField="Vendor_Name" HeaderText="Vendor" SortExpression="Vendor_Name" />

UPDATE:

Examining the View Source, the ID column header is represented as:

<th scope="col"><a href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$gvReq','Sort$Req_ID')">ID</a></th>

The first table row contains ID=70701, and this value appears in two other detail cells within the same row:

<tr onmouseover="this.style.backgroundColor='LightGray'" onmouseout="this.style.backgroundColor='White'">
  <td>70701</td>
  <td>206101</td>
  <td>EBM PAPST, INC</td>
  <td>6/26/2013</td>
  <td>58045 - HOT PO</td>
  <td>REPAIRS / db</td>
  <td align="center" style="color:Blue;width:50px;">
    <a onclick="javascript:popup_window=window.open('RequisitionDetails.aspx?Req_id=70701','ViewReqDetails','width=950,height=610,top=75,left=100,status=no, resizable= no, scrollbars=yes, toolbar= no,location= no, menubar=no,titlebar=no');popup_window.focus();" href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$gvReq','Select$0')" style="color:Blue;">Details</a>
  </td>
  <td align="center" style="width:50px;">
    <input type="submit" name="ctl00$ContentPlaceHolder1$gvReq$ctl02$btnDelete" value="Delete" onclick="showConfirm(this); return false;" id="ctl00_ContentPlaceHolder1_gvReq_ctl02_btnDelete" style="color:Red;" />
  </td>
</tr>

The desired ID value resides in a simple <td> tag.

Seeking assistance on incorporating this value into the existing setup.

OnClientClick="showConfirm(this); return false;"

Answer №1

function showConfirm(source) {
    ...
  }

If you want to enhance this method, consider updating the signature to accept more parameters, like itemName. You can also tweak the JavaScript to customize the text displayed in the popup (some HTML changes may be necessary). Take a look at the source code to see if it already has the required information.

EDIT

I experimented with this and found a simple solution using jQuery.

  1. Modify the popup's HTML structure to include a span for additional data:


    <div id="popupDiv" runat="server" align="center" class="confirm" style="display: none; background-color: white">
      <img align="absmiddle" src="Images/important.png" /><b>CONFIRM:</b> Delete <span id="popupDescription"></span>?<br />
      <asp:Button ID="btnOk" runat="server" Text="Yes" Width="50px" />
      <asp:Button ID="btnNo" runat="server" Text="No" Width="50px" />
    </div>

  1. Add a data-itemName="" attribute to the button in your grid with the item name as its value. Adjust the DataClass accordingly based on your data structure:


    <asp:Button ID="btnDelete" runat="server" CommandArgument='<%# Container.DataItemIndex %>' ForeColor="Red" CommandName="DeleteReq" data-itemName="<%# ((DataClass)Container.DataItem).Name %>" OnClientClick="showConfirm(this); return false;" Text="Delete" />

  1. Update the function to display this extra data in the popup:


    function showConfirm(source) {
        //Use jQuery to retrieve the data-itemName attribute value and set it in the span
        var sourceElement = $(source);
        var additionalInfo = sourceElement.attr('data-itemName');
        var descriptionElement = $('#popupDescription');
        descriptionElement.text(additionalInfo);
        this._source = source;
        this._popup = $find('mdlPopup');
        this._popup.show(); // Find the confirm ModalPopup and display it    
    }

Although not the most elegant solution, it gets the job done.

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

Is it possible to protect assets aside from JavaScript in Nodewebkit?

After coming across a post about securing the source code in a node-webkit desktop application on Stack Overflow, I began contemplating ways to safeguard my font files. Would using a snapshot approach, similar to the one mentioned in the post, be a viable ...

Solidjs: Implementing a Map in createStore does not trigger updates upon changes

As a beginner in solidjs, I might have missed something important. In the code snippet below, I am trying to understand an issue: const [state, setState] = createStore({ items: new Map() }); // e.g. Map<number, string> In a component, suppose I want ...

Storing pictures on an ASP.NET MVC site and securely storing them in a database

I am working on a project where the client needs to upload images of kitchens along with some text and a title for each image. Currently, my solution allows image uploads via URLs, but the client wants to be able to upload images directly from their comput ...

What is the best way to add a modal to every loop in a Jade template?

I've been working on a blogging engine using Node.js and jade. I have a section where I iterate through each post and add a button that allows users to delete the post. However, I've encountered a strange issue - when I click on the delete button ...

Navigating Through the DOM with Selenium using XPath Axes

Currently, I am developing Selenium tests for a dynamic web page. Within this section of code, I am extracting data from an Excel sheet and verifying if a specific element exists on the webpage. I have annotated the critical part of the code with comments ...

Having trouble with Cordova, Angular, and PushPlugin? Your callback isn't firing

While searching for solutions, I noticed various similar items but none were quite the same context as mine (Angular specifically, not using Ionic). My Cordova version is 5.0.0 (confirmed through 'cordova --version' in CMD showing 5.0.0, and in t ...

Error: We are facing an issue with new.mongoose.Schema as it is not functioning properly and

I am experiencing an issue with my product.js file. It keeps throwing an error about an unidentified identifier, and whenever I try to fix one problem, another one pops up. I have been struggling to locate the root cause of this error. ...

The randomness of a generated string is compromised if it is called multiple times

I'm having trouble generating a random string of words in a WebForms page using C# and ASP.NET. It works fine when called once, but when I call it multiple times in a row during a PostBack, it repeats the same random string each time. I suspect there ...

Steps for making a linked list through the drag-and-drop method

I'm attempting to make a dynamic list where users can drag and drop links from other websites, like a wishlist of sorts... <style> .droptarget { float: left; width: 100px; height: 35px; margin: 15px; padding: 10px; ...

The functionality of my button click is only operational on the initial attempt

I've configured a classic ASP.NET page on my SharePoint site that contains multiple buttons. Below is a snippet of the code: Button importZIPPOTBtn = new Button(); importZIPPOTBtn.Click += new EventHandler(importZIPPOTBtn_Cli ...

JS implementing a listener to modify a Google Map from a separate class

Currently, I am in the process of migrating my Google Map functionality from ionic-native to JavaScript. I am facing an issue while attempting to modify the click listener of my map from a separate class. The problem seems to be related to property errors. ...

JS/TS Strategies for Sharing Code Across Multiple Projects

Perhaps there is a different approach that has not crossed my mind. I have spent some time exploring various methods like js/ts with npm link, git submodules, tsconfig paths, symlink, npm/pnpm/yarn workspace, npm pack & npm link, package.json exports, ...

Elevating the mesh causes the ray caster to perceive it as though it has been flipped along the Y-axis

My raycaster seems to be detecting all my objects but in a flipped manner. It works fine when I add a cube without changing its position, but as soon as I move the cube up, the ray-casting goes downwards. Does anyone have a solution for this issue? Curren ...

"Implementation of Google+ button causing the appearance of a horizontal scrollbar

Adding Facebook and Twitter sharing buttons was easy, but now I'm having trouble with Google+. No matter where I place the code on my page (using a Bootstrap grid), it always adds 2-3 pixels on the right side, creating a horizontal scrollbar: <div ...

Decoding JavaScript content with Python

Currently, I am dissecting this specific portion of HTML <script type="text/javascript"> var spConfig = new Product.Config({"attributes":{"150":{"id":"150","code":"size_shoe","label":"Schuhgr\u00f6\u00dfe","options":[{"id":"494","label ...

Automatically change a text based on its location

Currently leveraging the amazing flexible-nav to showcase the current subtopic within my post. I am also considering the possibility of extracting this current-string and showcasing it at the top of the page in my main navigation bar. This way, the text w ...

Best practices for logging error objects in JavaScript

As a beginner in web development, I've recently come across an interesting observation related to handling errors. When working with json.stringyfy(), I noticed that the message key is not displayed in statement 2. However, accessing error.message ret ...

What are the steps to adjust the size of the Facebook "like" button?

Is there a way to modify the size of the Facebook like button? I attempted to adjust the padding of <a class="connect_widget_like_button clearfix like_button_no_like"> using jQuery, but was unsuccessful. Any suggestions on how this can be achieved? ...

The function cannot be called because the type does not have the appropriate signature for invoking. The specific type lacks compatible call signatures, as indicated

Encountering an issue while attempting to utilize a getter and setter in my service, resulting in the following error message: Cannot invoke an expression whose type lacks a call signature. Type 'Boolean' has no compatible call signatures 2349 t ...

Exploring dependency injection in Angular 1 using a blend of JavaScript and TypeScript

I'm currently working on integrating TypeScript into an existing Angular 1.5 application. Despite successfully using Angular services and third-party services, I am facing difficulties in injecting custom services that are written in vanilla JavaScrip ...