Reputation: 54117
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?
Upvotes: 8
Views: 17224
Reputation:
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.
Upvotes: 7
Reputation: 3208
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.
Upvotes: 18
Reputation: 13021
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.
Upvotes: 3
Reputation: 13099
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);
Upvotes: 0