开发者

Setting HyperLinkField to a Javascript Url

I have an issu开发者_运维技巧e where my Hyperlink field in Asp.net GridView is not accepting Javascript function that will open a popup dialog.

I am using the following snippet

 <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>  

However, when I use a page url, it works, e.g.:

DataNavigateUrlFormatString="~/SomeOtherPage.aspx?Id={0}"

Is there a way I can make this work with my JavaScript function?


I think you have to change it to a normal tag inside of a template field without using the asp:hyperlinkfield. Then you can do something like this:

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

All of your asp:hyperlinkfield attributes get placed on the templateField tag.

EDIT

You cannot place javascript in the hyperlinkfield, as this is by design


You can also use a bound field and then change the text in the RowDataBound event. (This will allow EnableSortingAndPagingCallbacks to work):

<asp:BoundField DataField="ID" HtmlEncode="False" />

Make sure HtmlEncode is 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜