[dba-VB] ASP.NET - pass data from .cs to .js

Gustav Brock gustav at cactus.dk
Wed Nov 21 10:39:29 CST 2012


Hi all

I have an ASP.NET winform project (.aspx) with a code-behind .cs file and an
included .js file for client side code.
The client side code is nothing special, only that it minimizes the
round-trip to the server which I found slowed down the page when run on a
smart-phone with GSM data link (not WiFi).

How can I pass data from the .cs code to the .js code?

Right now I write some client side script at Page_Load:

<c#>
private void RegisterScripts()
{
    // Output the reference to the .js file.
    Page.ClientScript.RegisterClientScriptInclude(this.GetType(), "jScript",
"/ClientScript.js");
 
    // Output the variables.
    StringBuilder sb = new StringBuilder();
    sb.Append("<script type=\"text/javascript\"
language=\"javascript\">\n");
    sb.AppendFormat("var optionsOne = new
Array(\"{0}\",\"{1}\",\"{2}\");\n", optionsAll[0,0], optionsAll[0,1],
optionsAll[0,2]);
    sb.AppendFormat("var optionsTwo = new
Array(\"{0}\",\"{1}\",\"{2}\");\n", optionsAll[1,0], optionsAll[1,1],
optionsAll[1,2]);
    sb.AppendFormat("var optionsThree = new
Array(\"{0}\",\"{1}\",\"{2}\");\n", optionsAll[2,0], optionsAll[2,1],
optionsAll[2,2]);
    sb.AppendFormat("var answerComments = new Array(\"{0}\",\"{1}\");\n",
answerComments[0], answerComments[1]);
    sb.AppendFormat("var alertEnterEmail = \"{0}\";\n", alertEnterEmail);
    sb.Append("</script>\n");
    Page.ClientScript.RegisterClientScriptBlock(GetType(), "fillOptions",
sb.ToString());
}
</c#>

This works fine and dandy as the data (the arrays and variables) are static
during a session (but not between sessions) as these are retrieved once from
the database also at Page_Load.

But the scriptblock is visible at client side if the user selects "View
source" in the browser and I would prefer it not to be.
Also, the method of writing code lines from code seems sort of primitive to
me.
Would there be a better/easier/smarter way?

/gustav



More information about the dba-VB mailing list