Javascript source code (aspx.cs) server side .Add to change label text

I am trying to change the text of a label using server side JavaScript (onclick) and C # on the page_load event. For example, I would like to write something like the following:

Label1.Attributes.Add("onclick", "Label2.text='new caption'")

      

Does anyone know the correct code for this? Also, what applies to this type of code; is it just JavaScript or JavaScript in C # or is there a specific name? Finally, is there a book or online resource that lists control.attributes.add ("event", "syntax") code options for use with C #?

+1


a source to share


2 answers


No server side Javascript (unless you switch to a non-ASP.NET framework where you are actually using Javascript as the server language). What you do is add an attribute to the html tag and the code will be executed entirely on the client side.

Let's first look at how this is done in HTML without server-side and server-side code:

<span onclick="document.getElementById('Label2').innerHTML='Thank you';">Click me</span>
<span id="Label2"></span>

      

Instead of using controls Label

, setting the onclick attribute from server side code, you should do the following:

Label1.Attributes.Add("onclick", "document.getElementById('Label2').innerHTML='Thank you';");

      



This will work as long as the controls are not inside a naming container. If they are, the ID of the controls is appended with the name of the container to keep them unique, so you need to use the property ClientID

to find out what their final ID is:

Label1.Attributes.Add("onclick", "document.getElementById('" + Label2.ClientID + "').innerHTML='Thank you';");

      

ClientID

always contains an ID that you can use to access the element from Javascript, so the latter code always works regardless of whether the control is in a naming container or not.

To see what attributes you can use, you should look at the HTML documentation, such as the Internet Explorer documentation for the span element.If you look at the documentation for a specific function, take a look at the standards information, as this will tell you if it works in any browser or only in Internet Explorer.

+2


a source


The above code adds JavaScript to the server control displayed on the client. Take a look at this MSDN article - Using JavaScript Alongside ASP.NET for more information.



IIRC, you will need to reference Label2

by its ClientID and you will need to write JavaScript to change the value of the label text (I think ASP.NET labels are obtained as tags <span>

).

+1


a source







All Articles