Monday, November 21, 2011

Javascript in usercontrol and custom control

In this article i will tell you how to add javascript in user control(Embedded source) and custom control
First if you have user control then you need to convert into custom control for this you read my article of this month DLL for user control.
if you have custom control open the Assembly.cs file

Step 1: Create javascript file and add into the solution
Step 2: please make sure your javascript should not have '<%= Control.ClientID %>' beacuse register start up script will not allow to find the control

Step 3: Use below javascript for finding the control in usercontrol or gridview

 function GetClientId(strid)
{
     var count=document.forms[0].length;
     var i=0;
     var eleName;
     for (i=0; i < count; i++ )
     {
       eleName=document.forms[0].elements[i].id;
       pos=eleName.indexOf(strid);
       if(pos>=0)  break;           
     }
    return eleName;
 }


Step 4: Change the build type to Embedded in your javascript file property.

Step 5:  In Assembly.cs file add line
[assembly:WebResource("Virtual_KeyBoard.VKScript.js", "text/javascript")], you need web.Ui package for this. In my case VKScript is the name of the javascript





Step 6:  Override the OnPreRender function in class file of solution  and add below lines

There are two different -2 technique to embedded the javascript

Technique 1:

ClientScriptManager cs = this.Page.ClientScript;
            using (StreamReader reader = new StreamReader(this.GetType().Assembly.GetManifestResourceStream(GetType(), "VKScript.js")))
            {
                string scriptCode = reader.ReadToEnd();
                cs.RegisterClientScriptBlock(this.GetType(),"Javascript", scriptCode, true);
            }

"This will show the script in page souce"

Techinique 2:
string resouce = "Virtual_KeyBoard.VKScript.js";
ClientScriptManager cs = this.Page.ClientScript;
cs.RegisterClientScriptResource(typeof(VirtualKeyBoard), resouce);

Webresouce.axd dynamically create script
example

<script src="/WebResource.axd?d=VGoSv7soghuqEqTXl_W8OcnRS_O6Sg_HFkP0Q7N6Kx3NtQ9dpBsCA7PnQRnxaS883X54KD66o8kcW6NDHr7vpRMHM5sNF6B2Fsn7tArccVnRO03aF55GsI6Dz12tfkiF3AW04g2&t=634574601134363084" type="text/javascript"> 
script>

Thanks for reading this article. if you like this article please comment on this article.



No comments: