Referencing server controls from Javascript

 Rate It (1)

 

In this article we will show you how to reference server side controls from JavaScript code (A server control is a control that has a runat="server" attribute).

Generally, every server control has an ID on the server side. One common problem when accessing the server side controls from JavaScript is that developers assume that the control's server side ID can be used directly in JavaScript code to reference the rendered control on the client side.  This is incorrect assumption.

The client side ID of the rendered control is not always the same as the ID on the server side. If you have placed the server side control inside another control which implements the INamingContainer marker Interface, the runtime will change the controls client side ID to enforce the uniqueness of that ID in the rendered html document. You can get the resulting client side ID through the controls ClientID property.

Note: You will notice this behavior when you start working with MasterPages or when you place the control inside GridView control or any other control that implements INamingContainer Marker Interface.

The following example will show you how to reference the Input control using its ClientID property:

<script language="javascript" type="text/javascript">
function incrementValue() {
var txtToIncr = document.getElementById('<%= txtToIncr.ClientID %>');
var CurrentValue = 0;
if (txtToIncr.value != '')
CurrentValue = parseInt(txtToIncr.value);
txtToIncr.value = CurrentValue + 1;
}
</script>

<div>
<input id="txtToIncr" type="text" runat="server" value="0" />
<asp:Button ID="BtnIncrement" runat="server" Text="Increment From Client Side" UseSubmitBehavior="false"
OnClientClick=" return incrementValue();" />
<asp:Button ID="BtnIncrementFromServer" runat="server" Text="Increment From Server Side" />
</div>

Code Behind:

Protected Sub BtnIncrementServer_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnIncrementServer.Click
Dim Currentvalue As Integer = 0
If (txtToIncr.Value <> "") Then
Currentvalue = Integer.Parse(txtToIncr.Value)
End If
txtToIncr.Value = Currentvalue + 1
End Sub

In the example, there are two TextBox controls.  The first one "BtnIncrement" can be used to change the Input control value via JavaScript code and the other control "BtnIncrementFromServer" is used to change the Input value from server side code.

 

Revision number 4, Monday, September 22, 2008 8:41:56 PM by mbanavige

Comments

Nice article

Nice simple article. A lot of developers seem to shy away from javascript, but it is this easy to modify a client page without a postback. Reducing server traffic and meaning the client doesn't have to wait for the server round trip.

This is not a very good way of doing it and it only works when you JavaScript is embedded in your ASPX Source. If you truly want to take advantage of JS nowadays, you have the JS in a seperate file so you can debug it. However, how do you get the server control reference? Easy, there's a little pattern I like to call, the "Script Registration" pattern. Basically, this is a function I add to any page that needs to register some server-side controls for use client-side: In your code behind of the Page. This also takes into account AsyncPostBacks that occur through an UpdatePanel: private void RegisterScripts() { System.Text.StringBuilder script = new System.Text.StringBuilder(); script.AppendFormat("ver txtFirstName = $get('{0}');\n", this.txtFirstName.ClientID); script.AppendFormat("ver txtLastName = $get('{0}');\n", this.txtLastName.ClientID); string scriptKey = this.ClientID; ScriptManager sm = ScriptManager.GetCurrent(this); if (sm != null && sm.IsInAsyncPostBack) ScriptManager.RegisterStartupScript(this, this.GetType(), scriptKey, script.ToString(), true); else Page.ClientScript.RegisterStartupScript(this.GetType(), scriptKey, script.ToString(), true); } Now, in your JavaScript there is never a need to use "getElementById" ever again! function doSomething() { txtFirstName.value = "My First"; txtLastName.value = "My Last"; }

Wow, this comment thing REALLY screws up all the formatting! Sorry about that guys!

Good one.. For beginners in Javascript.

Shortcuts

Table of Contents

Top Wiki Contributors

(last 30 days)

  1. mbanavige (5)
  2. SGWellens (4)
  3. maartenba (2)
  4. rami_nassar (2)
  5. stiansol (2)
  6. MisterFantastic (2)
  7. satish1.v (1)
  8. raklos (1)
  9. mosessaur (1)
  10. Jos Branders (1)

Advertise Here

Microsoft Communities
Page view counter