Welcome to SpellCoder Sign in | Join | Help

Javascript tricks for ASP.net developers

This is a post I wanted to write really long time ago, but I never had enough time to sit and write.
The following listing will be my agenda for this post
  1. Why Javascript for ASP.net developers is different ?
  2. Javascript tricks for ASP.net developers
    • Reading ASP.net controls values from Javascript
    • Passing values calculated by Javascript to the server side.
    • Passing values from ASP.net to Javascript
  3. Javascript development tools
So let's go through the previous points and see if this will be interesting enough for you to read it to the end.

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 UseControl 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
I think 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 comes 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 , buy 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">
function myFunc()
{
var myTextBox = document.getElementById("<%= myTextBox.ClientID %>");
myTextBox.value = "value from JS";
}
</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 a asp.net code which is written  <%= myTextBox.ClientID %>
and this how myFunc code will be in the browser.
<script type="text/javascript">
function myFunc()
{
var myTextBox = document.getElementById("MyControl1_myTextBox");
myTextBox.value = "value from JS";
}
</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 a 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 post 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

My Text

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">
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.

Javascript development tools
If you decided to write some code in Javascript so be ready and use the proper tools
  1. First of all I prefer you develop your code on FireFox because it is more strict and if you made your code run fine on FireFox most probably it will run fine on every other browser.
  2. Second you need Debugger so I strongly recommend FireBug which is an addin to FireFox which has lots of useful tools one of those tools is a Javascript debugger
  3. Visual Studio is a good IDE however there is another IDE especially dedicated to Javascript which is APTANA , aptana also provides a debugger for FireFox  so you can use Aptana debugger to debug your javascript running in FireFox
So that's what I could write in a single post, soon I will post some hints and tricks for developers to make it easier for them to write AJAX applications without using UpdatePanel.
Have fun.
kick it on DotNetKicks.com
Published Sunday, June 17, 2007 11:28 AM by Mohammed Hossam
Filed Under: ,

Comments

# re: Javascript tricks for ASP.net developers

Monday, June 18, 2007 1:25 PM by Sashidhar Kokku
Don't you think that trying to use scriptlets within script tags is as good as making a server side call.

The idea of having JS, is to avoid trips to the server.
-Sashidhar
(sashidhar.kokku at gmail.com)

# re: Javascript tricks for ASP.net developers

Tuesday, June 19, 2007 5:21 AM by alien
With the date, it seems like too much hassle to me. The following should work even without server side code:
<script type="text/javascript">
var serverDate = '<%= DateTime.Now.ToShortDateString() %>';
</script>

# re: Javascript tricks for ASP.net developers

Tuesday, June 19, 2007 8:43 AM by Mohammed Hossam
@Alien
The date was just an example, but sometimes you need to initialize an array in the javascript using values from database, so this technique will help

# re: Javascript tricks for ASP.net developers

Wednesday, June 20, 2007 5:44 AM by Ahmed A. Baghdadi
Thanks for these useful informations especially  passing value from asp.net to javascript.
Firebug is a powerful addin that i always use it.

# re: Javascript tricks for ASP.net developers

Wednesday, June 20, 2007 11:26 AM by Mohamed El-Sayed
Nice Post ya Mohammed.
KUTGW.

# re: Javascript tricks for ASP.net developers

Thursday, June 21, 2007 5:27 AM by sammy
Hi Mohd,
I face difficulty with getting several input boxes ID which are generated dynamically with javascript. I have tried FindControl method but the input seems like doesn't runat server although I have the runat=server in the code.
Then, I tried with hidden input, but the problem is I don't have any control to fire the event, as I already have the Save button to run certain c sharp code while the <Body> has to carry its own onload function.
What do u think?
Highly appreciate if you can give me a piece of advise.

# re: Javascript tricks for ASP.net developers

Thursday, June 21, 2007 6:53 AM by Ahmed A. Baghdadi
for passing value from asp.net to javascript i   used before another way to pass value e.g.

in aspx page
<script type="text/javascript">
var ServerValue;
//use it in anywhere u want
</script>

in cs
protected void Page_Load(object sender, EventArgs e)
{
Page.RegisterClientScriptBlock("anyname,\" <script language=javascript>ServerValue="+ txtBox.Text+"</script>");
}
 "

# re: Javascript tricks for ASP.net developers

Thursday, June 21, 2007 8:07 AM by anooor
nice post
but it is wellknown to all ASP.Net developers ;)

# re: Javascript tricks for ASP.net developers

Tuesday, June 26, 2007 4:18 AM by samer
Thank you for this nice post,

I would like to ask you the following:

1- how can I refer to infragistics controls in javascript?
2- how can I disable infragistics controls in javascript?

Best Regards

# re: Javascript tricks for ASP.net developers

Wednesday, June 27, 2007 5:58 AM by Mohammed Hossam
@samer
Sorry I didn't use Infragisitics controls before, so I don't know :(

# re: Javascript tricks for ASP.net developers

Friday, July 06, 2007 12:43 PM by Binish
awesome maaan.........fantastic!!!

# re: Javascript tricks for ASP.net developers

Thursday, July 12, 2007 1:57 PM by Anatoly
That is great!
It helped to solve my problem.
Thank you

# re: Javascript tricks for ASP.net developers

Sunday, July 29, 2007 2:38 PM by dgoepfrich
Great stuff!  But I have a question: I need to retrieve the client browser's date at Page_Load so I can use it in the C# codebehind, instead of the server date.

Essentially, I need the web app to act as if it's local to each user.  How can I get that date to the codebehind right away?

Thanks

Daniel

# re: Javascript tricks for ASP.net developers

Friday, August 03, 2007 5:06 AM by Chris
brilliant, thanks. This is just what I was looking for.  I am developing a basic management game to try to improve my dot net skills and was having trouble passing data from the client (which is affected by some javascript rollovers etc) back to the server.

Great work thanks.

# re: Javascript tricks for ASP.net developers

Saturday, September 15, 2007 1:25 AM by wwli
thanks man, great post!!

# Javascript tricks for ASP.net developers

Friday, September 21, 2007 9:59 AM by Rishi Songara
This is JavaScript Code, I have copied it from another site, but I m not getting the logic that why a Dollar ($) sign is been used in this piece of code, can anyone, explain it ??

function pageLoad(args){
           //  get all of the th elements from the gridview
           _ths = $get('gvCustomers').getElementsByTagName('TH');
           //  if the grid has at least one th element
           if(_ths.length > 1){
           
               for(i = 0; i < _ths.length; i++){
                   //  determine the widths
                   _thsIdea <img src=" />.style.width = Sys.UI.DomElement.getBounds(_thsIdea <img src=" />).width + 'px';
               
                   //  attach the mousemove and mousedown events
                   if(i < _ths.length - 1){
                       $addHandler(_thsIdea <img src=" />, 'mousemove', _onMouseMove);
                       $addHandler(_thsIdea <img src=" />, 'mousedown', _onMouseDown);
                   }
               }

               //  add a global mouseup handler            
               $addHandler(document, 'mouseup', _onMouseUp);
               //  add a global selectstart handler
               $addHandler(document, 'selectstart', _onSelectStart);
           }      
       }

# re: Javascript tricks for ASP.net developers

Friday, September 21, 2007 11:28 AM by Mohammed Hossam
This code is using Microsoft AJAX Extension and the $get is a shortcut of document.getElementById
and so the $addHandle is also another shortcut

# re: Javascript tricks for ASP.net developers

Saturday, October 27, 2007 3:37 PM by Morteza
great, thank you
Anonymous comments are disabled