views:

186

answers:

4

I'm developing a custom control with it's own style and script block inside the ascx-file.
All works fine, but if I use my control inside my aspx-page more the once, the script and style blocks are also repeated.

How to avoid this?

A: 

As long as those blocks are in the custom control itself, you can do nothing to remove the repetition, you should consider moving them to another place, or adding them via code.

Edit: My answer assumes you're complaining about repetitive links to script/styles files. However, if you're talking about full scripts inside the control, see _rick_schott's answer.

Moayad Mardini
A: 

Script

You can use the ClientScript object to register the script programatically in Page_Load instead of writing it in aspx:

if (!ClientScript.IsClientScriptBlockRegistered("myScript"))
{
    ClientScript.RegisterClientScriptBlock(GetType(), "myScript", "//the javascript code...", true);
}

Styles

For the styles, I don't know if it is any mechanisms to achieve this. Maybe you can use Theme mechanism. I have not used that myself so I don't know how it works...

awe
A: 

The only way I can think of to do this is to split the custom control into sub-controls.

Create a "Body" control as a styleless and scriptless control. Then, create a "Designer" control that you use to suck in multiple "Body" controls. Then you can add the "Designer" control to the aspx page once.

If you don't know how many "Body" parts" you need at compile time, add a paramater to the "Designer" control that allows you to dynamically add "Main Parts" from code behind at runtime.

BTW, if you have never used dynamic controls before, have fun!

BenB
A: 

Thanks for all answers. I just created a "helper" control which creates my styles and scripts, which I put only once on my aspx page. So I can add multiple instances of my actual control without redundant code.

Ulli