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

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

I wanted to do something like this:

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

    Just to chime in on this issue, I used a label in my .aspx page that was only to be visible in my DataList Item template if there were child records in the dataset.

    I added a onclick function to the label:

    moreOptionsLabel.Attributes.Add("onclick", string.Format("toggle_visibility('{0}')", div.ClientID));

    in my .cs file. It will now control a div tag in the .aspx page to show or hide the records - because the onclick points to a client side javascript function. Notice the div.ClientID, that makes this workable in a datalist.

    As noted above - the span tag does indeed become functional with "onclick". And since the label control is rendered as a span after the page request, using the Addtribute.Add("onclick".... does work.

    The result is show/hide functionality of data with out doing a postback. If you use the LinkButton, or simlar controls - the postback and page reload is unavoidable - unless you want to get into some Ajax stuff.

    NOTE: the span tag won't look clickable unless you style it with an underline and hand cursor.

    Credit to this idea comes from Will Asrari over at http://www.willasrari.com/blog/display-nested-repeaters-and-gridviews-asynchronously/000292.aspx

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

    You need to create a class object that inherits from the label and onclick event handler which will be a method by yourslef and use your object as a custom label.

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

    If you want an onclick event, why don't you use a linkbutton, which has the onclientclick event:

    <asp:linkbutton id="lblMyLink" onclientclick="lblMyLink_Click" runat="server">My Label</asp:linkbutton>
    

    You can use CSS to make the link look like whatever you want

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

    you could always roll out your own control which produces a span, with the .net's standard postback javascript, but as stated earlier using a linklabel with a CSS class would be easier

    0 讨论(0)
提交回复
热议问题