I\'d like to use string constants on both sides, in C# on server and in Javascript on client. I encapsulate my constants in C# class
namespace MyModel
{
The way you are using it is dangerous. Imagine some of your constants contained a quote, or even worse some other dangerous characters => that would break your javascripts.
I would recommend you writing a controller action which will serve all constants as javascript:
public ActionResult Constants()
{
var constants = typeof(Constants)
.GetFields()
.ToDictionary(x => x.Name, x => x.GetValue(null));
var json = new JavaScriptSerializer().Serialize(constants);
return JavaScript("var constants = " + json + ";");
}
and then in your layout reference this script:
Now whenever you need a constant in your scripts simply use it by name: