Is there a way to add an onclick event to an ASP.NET Label server control?

前端 未结 10 1005
不思量自难忘°
不思量自难忘° 2020-12-15 03:30

I wanted to do something like this:

My Label
相关标签:
10条回答
  • 2020-12-15 03:57

    Another hack would be to use a hidden link or button with style="display:none;" and trigger the click on the server control from a javascript function in the span.

    Something like this:

    <asp:linkbutton id="lblMyLink" onClick="lblMyLink_Click" runat="server" style="display:none;">My Link</asp:linkbutton>
    <span onclick="document.getElementById('lblMyLink').click();">My Label</span>
    
    0 讨论(0)
  • 2020-12-15 03:58

    You can do it in code in the page_load eg:

    void Page_Load(object sender, EventArgs e) 
    {
          lblMyLabel.Attributes.Add("onclick",
               "javascript:alert('ALERT ALERT!!!')");
    }
    
    0 讨论(0)
  • 2020-12-15 04:03

    As far as I know that's impossible. Label control emits <span> element which is “unclickable” on the server side. You would need to replace your Label control with a LinkButton.

    0 讨论(0)
  • 2020-12-15 04:10

    I think you can, but it's a client-side onclick handler, not server side. It will complain about the attribute not being supported (or some such) but I think it renders correctly. If you want to to a server-side handler, I think you'll need to do a LinkButton.

    0 讨论(0)
  • 2020-12-15 04:11

    Your question doesn't specify if you mean to raise the click event on the server (VB or c#) or the client (javascript.) If you're looking for a server-side event you should use a link button with css that makes the link appear as a label. You can then use the link button's server-side click event. If you're looking for a client-side click event - just type it into your server control markup
    asp:label id="MyLabel" runat="server" onclick="javascript:alert('hello');" Text="Click Me";
    ASP.NET will emit additional attributes in the html markup that generates.

    0 讨论(0)
  • 2020-12-15 04:14

    You can use Attributes to add onclick client side callback.

    I didn't know you can do this on span tags, but if it works you can add 'onclick' by lblMyLabel.Attributes.Add("onclick", "foo();");

    But foo(); would need to be a client side javascript function.

    System.Web.UI.WebControls.Label does NOT have OnClick server event. You could look into using AJAX if you want server callback with example above.

    You could also use LinkButton like other say. You can make it not look like a link by using CSS, if it is just that underline you are concerned about.

    ASPX:

    <asp:LinkButton ID="LinkButton1" runat="server" 
        CssClass="imjusttext" OnClick="LinkButton1_Click">
    LinkButton
    </asp:LinkButton>
    

    CSS:

    a.imjusttext{ color: #000000; text-decoration: none; }
    a.imjusttext:hover { text-decoration: none; }
    
    0 讨论(0)
提交回复
热议问题