How to write javascript in code behind file?

Below is a snapshot of my code that includes javascript taken from the gridview element template. It also has an image control.

<ItemTemplate> <a href="javascript:ShowChildGrid('div<%# Eval("ID#") %>');"> <img id="imgdiv<%# Eval("ID#") %>" alt="Click" border="0" src="plus.gif" /> </a> </ItemTemplate> 

The JS function takes an argument as an identifier. Now, how can I write JS in the code behind the file?

This is necessary because I need to display the image based on some condition in the row binding event in gridview.

PS: I am aware of the launch of Register Script and Client Script, but I'm not sure how they are suitable to meet my conditions.

+7
source share
2 answers

If you want to set JS code for each individual gridview element in a RowDataBound event, you can add hyperlink control to your ItemTemplate and set the NavigationUrl property of this control in JS

 <ItemTemplate> <asp:Hyperlink runat="server" id="lnk" ImageUrl="..."/> ... </ItemTemplate> 

RowDataBound-EventHandler:

 ... if (e.Row.RowType != DataControlRowType.DataRow) return; string js = String.Format("javascript:ShowChildGrid('div{0}');", rowId); var lnk = e.Row.FindControl("lnk") as Hyperlink; if(lnk!=null) { lnk.NavigationUrl = js; lnk.ImageUrl = ...; } 

Of course, you can also use a and img with runat -Attribute

+3
source

Change your template and use unobtrusive javascript.

 <ItemTemplate> <button class="imgdiv-button" data-img-id='<%# Eval("ID#") %>'> <img class="imgdiv" alt="Click" border="0" src="plus.gif" /> </button> </ItemTemplate> $(".imgdiv-button").click(function() { ShowChildGrid($(this).data('img-id')); }); 

Basically you need a button instead of a link (because it's a button). And you should just save this img-id in the data attribute.

+2
source

All Articles