Monday 31 January 2011

Asp.net web server control for rendering script blocks

There are many ways to add script block to our asp.net pages. This is a very simple problem until we had got a complex project with custom controls, partial page rendering, updatepanels and dynamically loaded controls.
We have to add script blocks different ways if we asynchrony post backs or full page post backs.
The other problem is when the script block don’t have to load at the first page load, it depends on some logic dynamically.

After many trying I use this solution since about half year and it works at any case.

The simple and easy to use source code is:

public class InlineScript : Control
    {
        protected override void Render(HtmlTextWriter writer)
        {
            StringBuilder sb = new StringBuilder();
            base.Render(new HtmlTextWriter(new StringWriter(sb)));

            string script = sb.ToString();

            ScriptManager sm = ScriptManager.GetCurrent(Page);
            if (!(null == sm))
            {
                if (sm.IsInAsyncPostBack)
                {
                    ScriptManager.RegisterStartupScript(this, typeof(InlineScript), UniqueID, script, false);
                }
                else
                {
                    base.Render(writer);
                }
            }
            else
            {
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), this.ID, sb.ToString());
            }
        }
    }

After registering into web.config, we can use it easily everywhere on our program:

<wc:InlineScript ID="isTest" runat="server">
    <script type="text/javascript">
        function pageLoad() {
            alert('hi');
        }
    </script>
</wc:InlineScript>

1 comment:

  1. Thank you. This is a very handy control (and works better than Telerik's RadScriptManager for my cases).

    ReplyDelete