eval is evil. You don't need to build JavaScript with server side code, it's a good way to cause yourself to have a massive headache.
To pass data to JavaScript, use custom [data-*] attributes and JSON.
ascx
<asp:ImageButton runat="server" ID="Button" />
ascx.cs
Button.Attributes["data-foo"] =
new {
bar = "baz",
fizz = "buzz"
}.ToJSON();
ToJSON extension method
public static string ToJSON(this object source)
{
var jss = new JavaScriptSerializer();
return jss.Serialize(source);
}
Access in JS via jQuery:
var foo;
foo = $('[data-foo]').data('foo');
console.log(foo.bar); //'baz'
console.log(foo.fizz); //'buzz';
One of the most important things about this setup is that C# will correctly JSON and HTML encode the data (in that order), following that, the JavaScript api will correctly decode the HTML attribute, and jQuery will correctly parse the JSON object.
What this means is that if you add special characters or encoded values to your C# object, you'll end up with those special characters or encoded values in your JavaScript object, without having to mess with anything to get it to work.
"