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)
Primary constants − Integer, float, and character are called as Primary constants. Secondary constants − Array, structures, pointers, Enum, etc., called as secondary constants.
Every C file that wants to use a global variable declared in another file must either #include the appropriate header file or have its own declaration of the variable. Have the variable declared for real in one file only.
There are various types of constants in C. It has two major categories- primary and secondary constants. Character constants, real constants, and integer constants, etc., are types of primary constants. Structure, array, pointer, union, etc., are types of secondary constants.
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="@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>
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.
public static HtmlString GetConstants(this HtmlHelper helper) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.AppendLine("<script type=\"text/javascript\">"); foreach (var prop in typeof(Constants).GetFields()) { sb.AppendLine(string.Format(" var {0} = '{1}'", prop.Name, prop.GetValue(null).ToString())); } sb.AppendLine("</script>"); return new HtmlString(sb.ToString()); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With