Share constants between C# and Javascript in MVC Razor

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:

<script type="text/javascript" src="https://stackoverflow.com/questions/6217028/@Url.Action("Constants")"></script>

Now whenever you need a constant in your scripts simply use it by name:

<script type="text/javascript">
    alert(constants.T_URL);
</script>

Leave a Comment