views:

89

answers:

1

Is it possible to create an ASP.NET server control that packages some javascript that will be emitted to the aspx page at design-time rather than run time? I am trying to create a control that will have "default" javascript. I can add jvascript using RegisterClientScriptBlock, but then a web developer can't modifiy the javascript - it is unavailable a design-time in this scenario. Is there a way to change the ToolBox properties so that when a web developer drops the control onto the page, the javascript is added in a separate script tag as well?

A: 

When I need to do this I make a property on the control that will inject the tags, and then the web dev makes a asp:literal tag that has visibility none and viewstate disabled, that has all the JS they need.

then in the page's code behind they inject the literal's text into the server controls properties.

<asp:Literal ID="Literal_HtmlHeader" runat="server" Visible="false" EnableViewState="false">
<script></script>
<style></style>
</asp:Literal>

there are probably better ways... but this is simple and effective for me.

protected void Page_Load(object sender, EventArgs e)
{

   if (!String.IsNullOrEmpty(this.Literal_HtmlHeader.Text.Trim()))
   {
       //inject css and js into header.
       Page.Header.Controls.Add(new LiteralControl(this.Literal_HtmlHeader.Text));

       // or add to your control cause it knows how to add the tags so there is no   duplication.
       ServerControl c = new ServerControl();
       c.HtmlHeaderCode = this.Literal_HtmlHeader.Text.Trim();
   }

}
BigBlondeViking