Wednesday, May 23, 2007

Re-Learning java scripts

For my current project of a credit management portal I had to re-visit java scripts to perform some client side validations. I have never got the chance to do JavaScripts with ASP.Net 2.0 and every simple damn thing abt those 2 technologies together was foreign to me and I had to learn from scratch. Thought I should just jot down a few things I've learnt along the way.

    1. Internationalizing the javascript messages 
      You can attach java scripts to the page at server side as oppose to writing the whole thing in the html page (or seperate java script file) it self as we use to. So at the server side u have all the localizations tools/APIs in your hand and you can pump localized content in to your javascript.     
      string javaScriptString = 'blah blah blah ' + Localization.GetString('Key',LocalResourceFile) Page.ClientScript.RegisterClientScriptBlock (this.GetType(),'NameOfScript',javaScriptString);
    2. Prevent Postback of a page                                           Again adding java scripts to client side events can be done at the server side.
      TextBox1.Attributes.Add('OnClick', 'showHelp') will call the showHelp javascript once the button is clicked by the user. But what happens by default is that the page anyway is sent to the server as a post back. In order to prevent it the attribute should be added as follows.
      TextBox1.Attributes.Add('OnClick','return showHelp').
      In this instance if the showHelp function returns false, the page will not be posted back.

Attaching the javascript to the page at server side and having event handlers bind at server side are two simple yet useful tricks I learnt. You can increse the flexibility of your event handling model (Eg: You can add and remove the attributes from a control based on server side logic) with this easily.

With the popularization of Ajax on web the importance of learning java scripts is again emphasized to the developer community.

Post a Comment