将HyperLinkField设置为JavaScript网址

5

我有一个问题,我的Asp.net GridView中的超链接字段不接受打开弹出窗口的Javascript函数。

我正在使用以下代码片段:

 <asp:GridView>
     <asp:HyperLinkField
         DataTextField="SomeColumn" HeaderText="Some Column Text"
         SortExpression="SomeColumn"
         HeaderStyle-HorizontalAlign="Left"
         DataNavigateUrlFormatString="javascript:LaunchSomePopupdialog({0})"
         DataNavigateUrlFields="Id"
         ItemStyle-Font-Underline="true" />  
 </asp:GridView>  

然而,当我使用页面网址时,它可以正常工作,例如:
DataNavigateUrlFormatString="~/SomeOtherPage.aspx?Id={0}"

有没有办法让我的JavaScript函数与此配合使用?
2个回答

7

我认为你需要将其更改为模板字段内的普通 a 标签,而不使用 asp:hyperlinkfield。然后你可以像这样做:

<asp:TemplateField HeaderText="Some Column Text" ItemStyle-Font-Underline="true">
    <ItemTemplate>
<a href="#" onclick="javascript:LaunchYourStuff('<%#Eval("YourColumnID")%>')"><%#Eval("YourColumnDisplayText")%></a>
     </ItemTemplate>
</asp:TemplateField>

您所有的asp:hyperlinkfield属性都会放置在templateField标记中。

编辑

您无法将JavaScript放置在hyperlinkfield中,因为这是按设计来的


1
你也可以使用绑定字段,然后在RowDataBound事件中更改文本。(这将允许EnableSortingAndPagingCallbacks工作):
<asp:BoundField DataField="ID" HtmlEncode="False" />

确保 HtmlEncode 为 false!

Protected Sub gv_RowDatabound(sender As Object, e As GridViewRowEventArgs) Handles gv.RowDataBound
    If e.Row.RowType <> DataControlRowType.DataRow Then
        Return
    End If
    Dim drv = TryCast(e.Row.DataItem, DataRowView)
    If drv Is Nothing Then
        Throw New Exception("drv is nothing")
    End If
    Const detailsCol As Integer = 4
    e.Row.Cells(detailsCol).Text = String.Format("<a href='javascript:popUp(""Details.aspx?ID={0}"");'>Details</a>", drv("ID"))
End Sub

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接