A colleague of mine today asked me a question regarding jQuery and wether or not it could be generated from server side C# code in asp.net.

A couple of solutions sprang to mind for her particular requirements, one of which was to pass in server side values to the script using Data Binding Expression Syntax “<% =this.Property %>” and the second was to dynamically inject the script in to the page.

The first solution offers more flexibility and is easier to change once your solution is deployed but the second option may also come in handy at times.



Take the very basic page shown below:

<htmlxmlns="http://www.w3.org/1999/xhtml"><headrunat="server"><title>title><scriptsrc="scripts/jquery.min.js"type="text/javascript">script>head><body><formid="form1"runat="server"><div><spanid="time-span">span><br/><span><% =this.CurrentDateTime %>span>div>form>body>html>

And the code in the page behind:

protectedvoid Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { StringBuilder sb = new StringBuilder(""); ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "RegisterTime", sb.ToString(), false); } } publicstring CurrentDateTime { get { return DateTime.Now.ToString(); } }

The first span in the element is set via jQuery from a snippet of javascript code that is generated on the server and injected in to the page via the ScriptManager.RegisterStartupScript method. Injected script shown below:

The second span simply calls the public property CurrentDateTime on the the page.

Now both of these achieve the same result and by no means is this any kind of useful example but it does demonstrate two different ways to achieve the same result.

The first option combines jQuery with server side code and may just be useful in more complex situations.

BondiGeek