Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting HyperLinkField to a Javascript Url

I have an issue 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?

like image 756
Julius A Avatar asked Jun 18 '10 10:06

Julius A


2 Answers

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

like image 53
Tommy Avatar answered Nov 10 '22 03:11

Tommy


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
like image 39
Bolo Avatar answered Nov 10 '22 01:11

Bolo