Writing JavaScript from a Custom Control

Posted by coffeeaddict on Stack Overflow See other posts from Stack Overflow or by coffeeaddict
Published on 2009-07-01T00:24:47Z Indexed on 2010/04/19 15:03 UTC
Read the original article Hit count: 138

Filed under:

I'm new to writing custom controls. I have MyCustomControl.cs and in my Render method I want to render out about 50 lines of JavaScript. What's the best way to do this, use the writer?

protected override void Render(HtmlTextWriter writer)
        {
            writer.write(@"<script type....rest of opening tag here");

            writer.Write(@"
                            function decode(s)
                            {
                                return s.replace(/&amp;/g, ""&"")
                                .replace(/&quot;/g, '""')
                                .replace(/&#039;/g, ""'"")
                                .replace(/&lt;/g, ""<"")
                                .replace(/&gt;/g, "">"");
                            };"
            );

I plan on having around 6 more writer.Write to write out some more sections here. Is that the best approach to actually perform the writing of JavaScript in this manor?

or should I use ClientScript.RegisterClientScriptBlock? So what's the best practice or common way people are writing javascript from a custom control? (I'm not talking about a user control here!!, custom control/Class!)

I also want to keep any indentation for readability once it's spit out/rendered on the client when viewing source.

© Stack Overflow or respective owner

Related posts about ASP.NET