Tuesday, September 12, 2006

Storing Static JavaScript in Resource File [ASP.NET 2.0]

In ASP.NET , we normally embedded the script string in the code-behind and invoke the RegisterStartupScript() to emit the JavaScript. The normal way we do like


ClientScriptManager csManager = Page.ClientScript;

StringBuilder strScript = new StringBuilder();
strScript.AppendLine("<script>");
strScript.AppendLine(@"var response = confirm('{0}, do you want to continue ?');","Alvin Chooi");
strScript.AppendLine("if(response)");
strScript.AppendLine(" alert('OK')");
strScript.Append("</script>");

if (!csManager.IsStartupScriptRegistered("ScriptTest"))
   csManager.RegisterStartupScript(this.GetType(), "ScriptTest", strScript.ToString());


The script is less readable and messy. What the worst is that would be a slightly string manipulation overhead. In ASP.NET 2.0, you can store this static script in the resource file resx, which is stored in the App_GlobalResources folder.

Screenshot



You could able to reference the script string from the resource file without hard-coding the script in the code-behind by


ClientScriptManager csManager = Page.ClientScript;

if (!csManager.IsStartupScriptRegistered("ScriptTest"))
{
  csManager.RegisterStartupScript(this.GetType(), "ScriptTest", String.Format(Resources.script.AlertMeScript,"Alvin Chooi"));
}



Neat and manageable !

No comments: