简体   繁体   中英

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.

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM