Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write Javascript in the code behind file?

Below is the snapshot of my code that includes javascript taken from gridview's item template. It also has an image control placed.

  <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 ID. Now how can i write the JS in the code behind file?

It is needed because i need to display the image based on some condition in row databound event of gridview.

P.S.: I am aware of Register Startup Script and Client Script but i am not sure how would they fit in to satisfy my conditions.

like image 487
xorpower Avatar asked Jul 29 '11 11:07

xorpower


2 Answers

If you want to set the JS code for each single item of the gridview in RowDataBound-event, you could add a Hyperlink-control to your ItemTemplate and set the NavigationUrl-property of this control to the 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 using the runat-Attribute

like image 176
Stephan Bauer Avatar answered Sep 28 '22 17:09

Stephan Bauer


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 want a button instead of a link (because it is a button). And you should just store that img-id in a data- attribute.

like image 21
Raynos Avatar answered Sep 28 '22 18:09

Raynos