Thursday 17 February 2011

Asp.Net: Add embedded Javascript to custom control

Question:
I'm building a custom web server control. How do I add embedded javascript code to my control?
How to load javascript from a custom control as Webresource?



Answer:
When you build a custom web control in Asp.Net you can either load your javascripts directly as files or leave this task to the webresource manager of the page.

If you want to use the second scenario
Follow these steps:
  1. Add js file to your control project in Visual Studio.
  2. Make the file an 'embedded resource'. (properties/build action)
  3. Add an assembly attribute that specifies the WebResource.
    // annotate your class or add this attribute to the AssemblyInfo class 
    [assembly: System.Web.UI.WebResource("MyNameSpace.Controls.Scripts.MyScript.js", "text/javascript", PerformSubstitution = false)]
    
  4. Register the javascript as client script resource.
    Page.ClientScript.RegisterClientScriptResource(typeof(MyNameSpace.Controls.MyControl), "MyNameSpace.Controls.Scripts.MyScript.js");
    

No comments: