ASP.Net Output Once Control
This is an article about outputting data to the browser only
once, specifying where it should be outputted. The result
is a control that can write out a single script to the header of the
.aspx file (as an example). This control can be downloaded at outputonce.zip.
While programming for the web I often find the need to have some output
sent to the client only once. A simple example is to include a
javascript file – or function – when it is required. This output need
usually arises while developing (dynamic) usercontrols.
Problem setting
1. Imagine a couple of usercontrols using the prototype.js file. The
usercontrols are not always loaded and there is thus no need to include
this file always and everywhere (don’t include it in the masterpage).
2. Imagine a repeater with formfields and some dynamic calculations
using a javascripted function. When the repeater does not contain any
data – there is no need to include the javascript function.
Solution
As an attempt to fix these issues I created a small control named
OutputOnce. This control makes use of a property called OutputKey and
the Page.ClientScript.IsClientScriptBlockRegistered and
Page.ClientScript.RegisterClientScriptBlock functions to ensure that
the script will only be rendered once. Additionally the control
contains an OutputLocation property to specify if the data should be
rendered INLINE or in the HEAD.
The ASP.Net code will look like
1: <uc:OutputOnce
2: ID=”outputonce”
3: OutputKey=”prototype”
4: OutputLocation=”Head”
5: runat=”server”>
6: <script type=”text/javascript” src=”prototype.js”></script>
7: </uc:OutputOnce>
Please find the code for this control at the top of this page. Known issues:
1. It is not possible to send the AjaxScriptManager to the HEAD.
Good luck, and please let me know of any issues.