I’ve found some interesting notes on ASP .NET’s GridView, it’s limitations and work arounds. For work I was looking for a way to execute JavaScript from clicking a link on a GridView Cell. An example would be to having a list of transactions and wanting to click a link to update it’s details. I noticed that many functions of GridView used <a> tags to execute JavaScript. An example would be:
[html]
<a href=”javascript:myFunction(‘variable’);”>Link</a>
[/html]
Since I had experience with the HyperLinkField before, I thought I would add a HyperLinkField to my GridView and set the DataNavigateUrlFields to the needed fields and the DataNavigateUrlFormatString to use the fields properly. I was hoping to accomplish it by using the following code, which in turn I found out this solution does not work:
[asp]
<asp:HyperLinkField DataNavigateUrlFields=”UserID,Date” DataNavigateUrlFormatString=”javascript:updatePanel(‘{0}’,'{1:d}’);”
HeaderText=”View” Text=”Details” />
[/asp]
It turns out that there is a bug with the DataNavigateUrlFormatString and HyperLinkField that when trying to use javascript inside, it strips the href attribute and leaves just a <a>Text</a>, not giving the user a link. I found information here at this forum post. This is as of ASP .NET 2.0 and I don’t know about 3.0 or 3.5. As show in the forum post, this is the correct way to insert JavaScript into your gridview:
[asp]
<asp:TemplateField HeaderText=”Details”>
<ItemStyle CssClass=”viewLines” />
<ItemTemplate>
<a id=”user<%# Eval(“userid”) %>” href=”javascript:updatePanel(‘<%# Eval(“userid”) %>’,'<%# Eval(“date”) %>’);”>View User</a>
</ItemTemplate>
</asp:TemplateField>
[/asp]
Now, using this technique I was able to use jQuery to insert a row below the clicked item and add additional information.
[html]
function updatePanel(user,date)
{
$(‘#LineItems’).remove(); // remove previous entries anywhere in the grid
// Now I got up two parents, to get to the TR tag, and I append after it another row with id’s so I can identifier them easily with jQuery.
$(‘#tran’+tran_id).parent().parent().after(‘
‘);
// I load the information through an ajax call
$(‘#LineItemsContent’).load(‘Details.aspx?u=’+user+’&date=’+date);
}
[/html]
I hope this can help people who are struggling to figure out why their HyperLinkFields won’t work correctly with JavaScript.
Justin
Thanks a TON, I spent alot of time trying to figure it out… and it works great. Thanks
LikeLike