Sometimes you happen to want a server side value to be available on the client side, to javascript. But doing so in a clean, modular way is not always trivial. Here’s my solution:
1. Add a hidden input field to the page.
2. Fill that field with values, as many as you’d like -> done with a method on the page.
3. Read those values on the client side -> done with a js function.
1. The hidden field in the aspx page:
<input runat=“server” type=“hidden” id=“Vars” class=“Vars” />
2. The method that adds the variable to the page:
internal void AddHiddenVarValue(string name, string value)
{
Vars.Attributes[name] = value;
}
3. The js function (assuming that jQuery is in use):
function GetGlobal(varName) {
return $(“.Vars”).attr(varName);
}
Some notes:
1. I added the class “Vars” to the hidden control because .net changes the id to something like “ctl00_Vars”.
2. Reasons for going for this solution:
A. It’s modular – as long as the “AddHiddenVarValue” method is compatible with the GetGlobal function you can change their behavior and not have to change anything about your global vars/values.
B. It’s easy to debug on the client side – all you have to do is view the page’s source and you can see if the values are as expected.
C. All the variables and their values are concentrated in the same place – very easy to manage and monitor.
D. Best of all – you don’t actually have to use global js vars or inject js code blocks into the page.
3. In this solution I’m adding meaningless attributes to the hidden control (from an HTML point of view). It is possible to encode all these values into the “value” attribute of the hidden control, but I didn’t bother. It’s nice enough for me as it is. 🙂