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
{
public static class Constants
{
public const string T_URL = "url";
public const string T_TEXT = "text";
. . .
}
}
I found a way to use these constants in Javascript using Razor syntax, but it looks weird to me:
@using MyModel
<script type="text/javascript">
var T_URL = '@Constants.T_URL';
var T_TEXT = '@Constants.T_TEXT';
. . .
var selValue = $('select#idTagType').val();
if (selValue == T_TEXT) { ...
Is there any more "elegant" way of sharing constants between C# and Javascript? (Or at least more automatic, so I do not have to make changes in two files)
You can use an HTML helper to output the script necessary, and use reflection to grab the fields and their values so it will automatically update.
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:
and then in your layout reference this script:
Now whenever you need a constant in your scripts simply use it by name:
My version to create a namespaced javascript object from my C# constants that is immutable:
Used like this in Razor:
Rather then storing your constant data in a C# class, store it in a static config/constants file.
Simply store it as some file format (json, xml, cvs, whatever) then load it up from both the client & server.
This means your either creating a class in the C# on the fly at runtime using black magic reflection or just have a hashtable / dictionary containing your constants under keys.
jQuery.getJSON
,JsonReaderWriterFactor