I found a neat little trick this past week. Probably something that all other programmers that are using data binding already knows…
In short, I needed to show JavaScript Confirm popup following the click event of a LinkButton contained in a GridView on an ASP.Net 4.0 framework web site page. If not familiar, a Confirm popup requires the user to select “OK” or “Cancel” to proceed. The text of this Confirm needed to include some data from an object and not just a hardcoded message. The GridView was data bound to a collection of objects. In this case, I needed to get that object property value into the text shown on the Confirm.
The typical use of EVAL is to extract a property of the current, data bound object and return it as an object. Typically, that object is a string and it is stuffed into or used by some control on the page (textbox, label, etc…).
The following is a fairly typical example of EVAL usage:
'<%# Eval("PropertyName") %>'
Assuming the value of the “PropertyName” property is “123”, the value return is “123”.
Thanks to overloads, another option is to format the property in a fashion much like a String.Format. Such as:
'<%# Eval("PropertyName", "The value is {0}") %>'
Which then returns “The value is 123” (Assuming the value of the “PropertyName” property is “123”).
This means that the second option can also be used to format the entire JavaScript Confirm statement, like this:
'<%# Eval("PropertyName","return confirm(""Item {1} is going to be deleted."")") %>'
When this is assigned to the OnClientClick event of an asp:LinkButton, the result is a client side, JavaScript popup confirmation asking the user “Item 123 is going to be deleted.” When the user response is “OK”, the server-side code is called. If “Cancel”, the click event is canceled on the client-side avoiding a round trip to the server.
Nice!
Now, believe me, I understand how annoying these pop-up, confirmation messages are and also fully aware that they are ignored by most users. However; this was a requirement of the web site being developed so not something I dreamed up on my own to annoy users. Hmmm…. now there’s an idea! 🙂
Leave a Reply