How to use JavaScript file from Embedded Resources in ASP.NET

Ok Imagine we are writing some rich Ajax asp.net control and we need to use javascript file. Of course we can do something like that(from msdn):

if (!cs.IsClientScriptBlockRegistered(cstype, csname2))
    {
      StringBuilder cstext2 = new StringBuilder();
      cstext2.Append("<script type=text/javascript> function DoClick() {");
      cstext2.Append("Form1.Message.value='Text from client script.'} </");
      cstext2.Append("script>");
      cs.RegisterClientScriptBlock(cstype, csname2, cstext2.ToString(), false);
    }

but it looks little bit ugly...
Insted of this we can add our JavaScript to our Assembly as embedded resource.
1. Go to Resources folder and choose Add (we are adding our js file)
2. In the properties of js file set   Build Action:Embedded Resource
3. In AssemblyInfo.cs add attribute assembly: WebResource("Controls.Resources.Script_include.js", "application/x-javascript")]  -
where Controls - name of Assembly; Resources  - where situated js file; Script_include.js - name of js file.
4. To use it In control add code:

protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            Page.ClientScript.RegisterClientScriptResource(typeof(MyControl), "Controls.Resources.Script_include.js");
         
        }

So now you can simply use your js file(but you also can add to resources in similar way css files and images)
I hope it helps you.

Kigorw Copyright© 2006 special for www.ajaxline.com

Comments

Page.ClientScript.RegisterClientScriptResource(typeof(MyControl), <===== mycontrol is?

Are you human

You can use simple HTML-formatting tags(like <b>, <ul>, <code> and others)

Are you human
search engine optimisation
Advertise on this site