Tuesday, April 19, 2011

Registering Scripts



Techniques to Add Scripts Programmatically to ASP.NET Pages

By Dino Esposito

ASP.NET pages are essentially server-side pages that perform most of their tasks on the server. These tasks are typically coded using managed languages and require the configuration of server controls so they can generate and send the expected markup to the browser. But what if you need to generate some client-side script code, as well? At the end of the day, script code is simply plain text wrapped by a proper ");
string js = builder.ToString();

The more complex the script, the more error prone this code turns out to be (as well as difficult to maintain and edit). A better approach might be using local templates of scripts with placeholders that you load into a string and then expand using the String.Format method:

string scriptTemplate = LoadScriptTemplate(...);
string js = String.Format(scriptTemplate, functionName,
 param1, param2, ...);

If you need to emit a lot of dynamically-generated script code in your pages, you might want to consider writing an ad hoc JavaScript builder class to simplify your task and come up with a more readable and less error-prone code than above. The JavaScript builder class will feature a programming interface similar to StringBuilder, except that it supplies ad hoc methods to add functions, variable declarations, and other JavaScript-typical constructs.

Let s assume you get your script done and saved in some memory variable. How can you have it embedded in the output stream being flushed to the browser?

USING THE PAGE CLASS FACILITIES

ASP.NET supports a subscription pattern for developers to publish their script code in the body of a Web page. In short, you have two main options: adding an explicit

No comments:

Post a Comment