ASP.NET Custom Server Control with lots of Embedded JavaScript and other Static Files

794 views Asked by At

I am trying to create a Custom Server Control with lots of JavaScript and other static files embedded.

My problem is how to bundle and register them easily. I have an approach as follows but I don't think it would be good idea to register every single javascript file one by one.

This is the code which I have put inside my AssemblyInfo.cs file :

[assembly: WebResource("CustomControl.Scripts.Default.js", "text/javascript")]

The following code is for my custom control to register the .js:

protected override void OnPreRender(EventArgs e) {

    base.OnPreRender(e);
    string resourceName = "CustomControl.Scripts.Default.js";

    ClientScriptManager cs = this.Page.ClientScript;
    cs.RegisterClientScriptResource(typeof(CustomControl.MyControl), resourceName);
}

Also, that would be great to reach out the file from the web application like below :

CustomControl/scripts/default.js
1

There are 1 answers

0
Asbjørn Ulsberg On

In Visual Studio, you can embed resources in the assembly and then programmatically retrieve them like so:

// TODO: Get the correct assembly, this is just an example.
var assembly = GetType().Assembly;
var resourceNames = assembly.GetManifestResourceNames();

foreach (var resourceName in resourceNames)
{
    using (var stream = assembly.GetManifestResourceStream(resourceName))
    {
        using (var reader = new StreamReader(stream))
        {
            // This will contain the contents of the embedded resource
            string resource = reader.ReadToEnd();
        }
    }
}

You of course need to adjust the above code to your requirements, but the basics should be the same.