As I was preparing some Proof-of-Concept for my new ASP.NET Webforms projects, I came across an idea of using a dynamic JavaScript. Here how it goes.
Let say I want to generate the following javascript dynamically
var currencyManager = function() {
var _currencyManager = function() {
this.list = [
{cur:'EUR',rate:0.69996},
{cur:'GBP',rate:0.61304},
{cur:'AUD',rate:0.93141}];
}
_currencyManager.prototype = {
getRate : function(currency) {
var rate = 0;
for (var i = 0; i < this.list.length; i++) {
if (this.list[i].cur === currency) {
rate = this.list[i].rate;
break;
}
}
return rate;
}
}
return new _currencyManager();
}();
From the above code, I want the list of currencies to be dynamic as I want my users to get the latest rates from our database
To implement this I created a Generic Script Handler (.ashx). The code will be similar to this one
public class CurrencyScriptHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { if (context == null) throw new NullReferenceException("context is null or not defined"); if (context.Response == null) throw new NullReferenceException("context.Response is null or not defined"); HttpResponse response = context.Response; StringBuilder stringBuilder = new StringBuilder(); StringWriter textWriter = new StringWriter(stringBuilder); HtmlTextWriter htmlWriter = new HtmlTextWriter(textWriter); Page page = new Page(); Control control = page.LoadControl("Scripts/CurrencyScriptControl.ascx"); page.Controls.Add(control); HttpContext.Server.Execute(page, textWriter, false); response.ContentType = "text/javascript"; response.Write(stringBuilder.ToString()); } public bool IsReusable { get { return false; } } }
As you may notice I am just rendering a User Control and setting the ContentType to “text/javascript”. The Control CurrencyScriptControl.ascx will contain the code to generate this javascript.
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="CurrencyScriptControl.ascx.cs" Inherits="Monday.Scripts.CurrencyScriptControl" %>
var currencyManager = function() {
var _currencyManager = function() {
this.list = <%= CurrencyListJson %>;
}
_currencyManager.prototype = {
getRate : function(currency) {
var rate = 0;
for (var i = 0; i < this.list.length; i++) {
if (this.list[i].cur === currency) {
rate = this.list[i].rate;
break;
}
}
return rate;
}
}
return new _currencyManager();
}();
The CurrencyListJson can be a protected property of your ascx control
public partial class CurrencyScriptControl : System.Web.UI.UserControl { protected string CurrencyListJson ; protected void Page_Load(object sender, EventArgs e) { CurrencyScriptControl = CurrencyListJson(); } private string CurrencyListJson() { // Call you business objects here and JSON serilizer. } }
We may now call this script into our page like this
<script type="text/javascript" src="Scripts/CurrencyScriptHandler.ashx"></script>