Server tag in OnClientClick

The following gives me an error of “The server tag is not well formed”

<asp:LinkButton ID="DeleteButton" runat="server" CommandName="Delete" 
    OnClientClick="return confirm('Are you sure you want to delete <%# Eval("Username") %>?');">
    Delete
</asp:LinkButton>

(This is used in a data bound ListView that displays a list of users. When you click the delete button a JavaScript confirm dialog is used to ask you if you’re sure)

So, how can I embed a server tag in a string that contains JavaScript?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The problem is the binding nugget and the use of single and double quotes.

<asp:LinkButton D="DeleteButton" runat="server" CommandName="Delete" OnClientClick='<%# CreateConfirmation(Eval("Username")) %>'>Delete</asp:LinkButton>

Then on the code-behind add the function…

Public Function CreateConfirmation(ByVal Username As String) As String
    Return String.Format("return confirm('Are you sure you want to delete {0}?');", Username)
End Function

When the binding nugget is used as the value for an attribute, you’ll note you have to use single quotes. Your script also needed quotes for the embedded string parameter to the confirm function. You basically ran out of quotes.

Method 2

I found this answer over at www.asp.net

OnClientClick='<%# Eval("ProductName", "return confirm(""Delete the Product {0}?"")" ) %>'

This puts everything in the markup so anyone doing maintenance later doesn’t have dig around to find all of the pieces.

Method 3

Add the code dynamically in the ItemDataBound event for the ListView control.

In your page_Load event add the following

lst.ItemDataBound += new EventHandler<ListViewItemEventArgs>(lst_ItemDataBound);

Then in your ItemDataBound event handler add

Control DeleteButton = e.Item.FindControl("DeleteButton");
DeleteButton.OnClientClick = string.Format( "return confirm('Are you sure you want to delete '{0}'?", Username);

This solution should work whether you use OnClientClick or Sachin Gaur’s solution.

Method 4

You can add the onclick event at run time, like this:

DeleteButton.Attributes.Add("onclick", "'return confirm('Are you sure you want to delete '" + Username);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x