在 MVC Razor 中在 C# 和 Javascript 之间共享常量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6217028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Share constants between C# and Javascript in MVC Razor
提问by VikVik
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
我想在两端都使用字符串常量,在服务器上的 C# 和客户端上的 Javascript 中。我将常量封装在 C# 类中
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:
我找到了一种使用 Razor 语法在 Javascript 中使用这些常量的方法,但对我来说看起来很奇怪:
@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)
在 C# 和 Javascript 之间有没有更“优雅”的共享常量的方式?(或者至少更自动,所以我不必在两个文件中进行更改)
回答by Darin Dimitrov
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.
你使用它的方式是危险的。想象一下你的一些常量包含一个引号,或者更糟糕的是一些其他危险的字符 => 会破坏你的 javascripts。
I would recommend you writing a controller action which will serve all constants as javascript:
我建议您编写一个控制器操作,它将所有常量作为 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>
回答by Jay
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.
您可以使用 HTML 帮助程序输出必要的脚本,并使用反射来获取字段及其值,以便自动更新。
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());
}
回答by bigbadmad
My version to create a namespaced javascript object from my C# constants that is immutable:
我从不可变的 C# 常量创建命名空间 javascript 对象的版本:
public static HtmlString GetConstants<T>()
{
StringBuilder jsConstant = new StringBuilder();
jsConstant.Append("myApp." + typeof(T).Name + " = Object.freeze({");
foreach(var item in typeof(T).GetFields())
{
jsConstant.Append(string.Format("{0}:'{1}'",item.Name,item.GetValue(null).ToString()) + ",");
}
jsConstant.Remove(jsConstant.Length - 1, 1);
jsConstant.Append("})");
return new HtmlString(jsConstant.ToString());
}
Used like this in Razor:
在 Razor 中像这样使用:
@(HtmlHelpers.GetConstants<MyApp.Infrastructure.ApplicationConstants.SomeConstants>())
回答by Raynos
Rather then storing your constant data in a C# class, store it in a static config/constants file.
与其将常量数据存储在 C# 类中,不如将其存储在静态配置/常量文件中。
// Constants.json
{
"T_URL": "url",
"T_TEXT": "text"
}
// Constants.cs
// load the json from a file stream into a constants object
// Constants.js
window.Constants = $.getJSON(url);
Simply store it as some file format (json, xml, cvs, whatever) then load it up from both the client & server.
只需将它存储为某种文件格式(json、xml、cvs 等),然后从客户端和服务器加载它。
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.
这意味着您要么在运行时使用黑魔法反射在 C# 中即时创建一个类,要么只拥有一个包含键下常量的哈希表/字典。