OnClientClick中的服务器标记

时间:2009-02-09 13:05:58

标签: asp.net

以下给出了“服务器标签格式不正确”的错误

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

(这用于显示用户列表的数据绑定ListView。当您单击删除按钮时,将使用JavaScript确认对话框询问您是否确定)

那么,如何在包含JavaScript的字符串中嵌入服务器标签?

4 个答案:

答案 0 :(得分:18)

问题在于绑定金块以及单引号和双引号的使用。

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

然后在代码隐藏中添加函数...

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

当绑定块用作属性的值时,您会注意到必须使用单引号。您的脚本还需要针对confirm函数的嵌入字符串参数的引号。你基本上用完了报价。

答案 1 :(得分:7)

我在www.asp.net

找到了这个答案
OnClientClick='<%# Eval("ProductName", "return confirm(""Delete the Product {0}?"")" ) %>'

这会将所有内容都放在标记中,以便后来进行维护的任何人都无法找到所有部分。

答案 2 :(得分:3)

在ListView控件的ItemDataBound事件中动态添加代码。

在page_Load事件中添加以下内容

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

然后在ItemDataBound事件处理程序中添加

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

无论您使用OnClientClick还是Sachin Gaur的解决方案,此解决方案都应该有效。

答案 3 :(得分:0)

您可以在运行时添加onclick事件,如下所示:

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


相关问题