JavaScript tricks for ASP.Net developers

Every ASP.Net site on the Internet has various user controls and almost every developer have to handle these controls in JavaScript. Most developers face problem finding these ASP.net user controls in JavaScript side.
If you have ever wanted to handle ASP.Net controls in JavaScript, this article should help you get started and demystify what seems to be mysterious task.

The following listing will be the agenda for this document.

  1. Why JavaScript for ASP.net developers is different?
  2. JavaScript tricks for ASP.net developers
    1. Reading ASP.net controls values from JavaScript
    2. Passing values calculated by JavaScript to the server side.
    3. Passing values from ASP.net to JavaScript
    4. Reading ASP.net controls values inside data grid from JavaScript

Why JavaScript for ASP.net developers is different

The first difference between ASP.net and other web technologies that it has its own web controls which sometimes map to standard HTML controls, so sometimes what you see in ASP.net as a control doesn’t mean that it will be rendered as one control in the final HTML which means that JavaScript can’t deal with it directly as it does with basic control.

Taking the ASP.net Calendar control as an example, in ASP.net you use it as one control just drag it and drop it in the page and boom! you have a full functional calendar, but in reality this calendar renders as a Table with rows and columns and links and also lots of JavaScript, so you can’t expect that you will deal with it as a calendar in the JavaScript side, this also applies to Repeater, Grid, DataList … etc

The second difference is that even with asp.net server controls that maps directly to standard HTML controls like Textbox or Button, the asp.net runtime changes the control Id’s so if placed a code like this in your ASP.net page directly.

<asp:TextBox ID="myTextBox" runat="server"></asp:TextBox>

the rendered equivalent HTML will look like this

<input type="text" id="myTextBox" name="myTextBox"/> 

As you can see the asp:TextBox id is the same as the input text id which is "myTextBox", but watch out, if you put the previous asp:TextBox in a UserControl instead of adding it directly to the page, and then added the UserControl to the page like this lets name our usercontrol "MyControl".

<uc1:MyControl ID="MyControl1" runat="server" /> 

the rendered equivalent HTML will look like this

<input type="text" id="MyControl1_myTextBox" name="MyControl1$myTextBox"/>

As you can see the rendered input field Id is not "myTextBox" but it is a combination of the usercontrol id and the textbox id separated by underscore "_" and the name of the control is similar but separated by dollar sign "$".

So that’s why you will face some difficulties when you try to use document.getElementById on the "myTextBox" because the name is not known until the page renders.

JavaScript tricks for ASP.net developers

Reading ASP.net Controls Values from JavaScript

Now you have seen the problem and it is time for the solution so let’s see the basic solutions for most of JavaScript problems with ASP.net. The solutions come from the fact that almost all ASP.net controls have a property called ClientID which returns the Id of the rendered equivalent HTML control. So in our last Example the myTextBox.ClientID will return "MyControl1_myTextBox" so you can apply the document.getElementById, but wait a second how could I get this property value inside my JavaScript code?

This will require writing some ASP classic style code to this job inside the JavaScript so let’s see how our UserControl code will look like

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="MyControl.ascx.cs" Inherits="MyControl" %> 

<script type="text/javascript">
   1:  

   2: function myFunc() 

   3: { 

   4: var myTextBox = document.getElementById("<%= 

   5: myTextBox.ClientID %>"); 

   6: myTextBox.value = "value from JS"; 

   7: } 

</script>

<asp:TextBox ID="myTextBox" runat="server"></asp:TextBox> 

<input type="button" value="Click" onclick="myFunc()" /> 

So if you have a look into the myFunc function the document.getElementById parameter is actually an asp.net code which is written <%= myTextBox.ClientID%> and this how myFunc code will be in the browser.

<script type="text/javascript">
   1:  

   2: function myFunc() 

   3: { 

   4: var myTextBox = document.getElementById("MyControl1_myTextBox"); 

   5: myTextBox.value = "value from JS"; 

   6: } 

</script>

So the asp.net code between the <%%> is executed and the property ClientID was evaluated.

Passing values calculated by JavaScript to the server side

Yeah this is very important, sometimes you calculate some values or get some inputs from the user using Javascript code but you want to process these result in the backend, and you find yourself asking this question, how can I send those results back to the asp.net?

The answer is simple use your best friend The HiddenField.

Write all your results in the hidden field BUT make sure that this hidden field is either an asp:HiddenField or a regular input type="hidden" field with runat="server" attribute, so the asp.net runtime picks its value from the form and posts it to the field in the backend.

Passing values from ASP.net to JavaScript

Sometimes you need to pass values or initialize some variables in javascript using code behind, in this case you need to use your other friend the Literal Control The literal control is amazing because it simply renders to nothing but the values inside, so it doesn’t render to Span like Label or div like Panel, so take this example

<asp:Literal runat="server" ID="litData">My Text</asp:Literal> 

This code will render to this

Consider the example when you need to use the server date in the client javascript code, because the javascript Date function returns the client date so sometimes you need to use the Server time not the client time, so this is a way to do it using the Literal trick.

In your asp.net markup code define a similar javascript block

<script type="text/javascript">
   1: var serverDate = '<asp:literal runat="server" id="litServerDate"></asp:literal>';

</script>

and then in your Page_Load code you can do this

protected void Page_Load(object sender, EventArgs e)

{

litServerDate.Text = DateTime.Now.ToShortDateString();

}

In the javascript code you define a variable which takes its value from a literal control, the literal control is your connection to the backend code, the backend code puts the data inside the literal and completes the javascript sentence, so the result javascript will look like this

<script type="text/javascript">

var serverDate = '6/17/2007';

</script> 

So the literal is gone and the result is just the date string provided by the server,which you can use later to do whatever you want.

Reading ASP.net controls values inside data grid from JavaScript

Now we have seen how to read ASP.net controls values from JavaScript, let us now consider a special case of how to read ASP.net controls in a datagrid template column using Javascript.

There can be several ways in which you want to read the template column. Let us take one such case to illustrate how you can read data from template column in a datagrid.

Case: There might be a situation where you want to read columns in a datagrid or based on some condition want to get particular columns data. For this case you can have a javascript like this

<script type="text/javascript">

function GetGridColumnJSName()

{

    for(i=0; i<form1.length; i++)

    {

        var Name = form1.elements[i].id

        if (Name.indexOf("TextBox1") != -1)

        {

            document.getElementById(Name).value;

        }

    }

}

</script> 

In the above code snippet loop through all the controls in the form, then check for the existence of template column name (“TextBox1” in our Case example) in the control name. If it exists you can get the value of that control.

You can have certain conditions on the returned value like value should not be “null” or any other condition with this.

Conclusion

You can handle ASP.net controls using JavaScript in many ways. This article has shown you a brief description of various techniques to handle ASP.net Controls using Javascript. You can refer to description, code and scripts in this article to handle ASP.net control using JavaScript in your own Web site.

Related Posts

  1. ASP.Net Performance Improvement Tips
  2. Checklist/Guidelines for ASP.Net Developers
  3. ASP.Net Developers Checklist – Security Checklist
  4. ASP.Net Tutorial: Wizard Control
  5. Call ASP.net MVC Server side function using Jquery Ajax

Tags: , , , , , , , ,

One Comment to “Handling ASP.Net Controls in JavaScript”

  1. Lata says:

    Thanks, it helpful to me.

Leave a Reply

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>