简体   繁体   中英

How can I make my webpage run JavaScript code when an ASP.net control is clicked?

I have a web page that uses the ASP.net Tree View web control. As the web page is currently programmed, when the user clicks on a node on the tree view, the page posts back and a C# function executes to handle the event.

Can I make my web page run some Javascript code and not post back when a tree view node is clicked?

Suppose my page looks like the one below. 假设我的页面如下图所示。 How can I make it so that clicking on node_A is handled by Javascript client-side instead of C# server-side?

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication3.WebForm2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<body>
    <form id="form1" runat="server">
    <div>
    <asp:TreeView runat="server" ID="myTreeView">
    <Nodes>
        <asp:TreeNode Text="node_A" Value="1" />
        <asp:TreeNode Text="node_B" Value="2" />
        <asp:TreeNode Text="node_C" Value="3" />
    </Nodes>
    </asp:TreeView>
    </div>
    </form>
</body>
</html>

Bind a click event on your elements, get the event object and call preventDefault() .

element.onclick = function(e) {
    var evt = window.event || e;
    evt.preventDefault();

    /* Your code */
}

jQuery shortcut

$("element").click(function(e){ e.preventDefault(); });

Did you try:
EnableViewState="False"

or
can you remove the runat server ?

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