在MVC Razor中分享C#和Javascript之间的常量

Vik*_*Vik 31 javascript razor asp.net-mvc-3

我想在服务器上的C#和客户端的Javascript中使用字符串常量.我将我的常量封装在C#类中

namespace MyModel
{
        public static class Constants
        {
            public const string T_URL = "url";
            public const string T_TEXT = "text";
     . . .
        }
}
Run Code Online (Sandbox Code Playgroud)

我找到了一种使用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) { ... 
Run Code Online (Sandbox Code Playgroud)

是否有更优雅的方式在C#和Javascript之间共享常量?(或者至少更自动,所以我不必在两个文件中进行更改)

Dar*_*rov 78

你使用它的方式很危险.想象一下你的一些常量包含一个引用,甚至更糟糕的一些其他危险的字符=>会破坏你的javascripts.

我建议你编写一个控制器动作,它将以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 + ";");
}
Run Code Online (Sandbox Code Playgroud)

然后在你的布局中引用这个脚本:

<script type="text/javascript" src="@Url.Action("Constants")"></script>
Run Code Online (Sandbox Code Playgroud)

现在,无论何时需要脚本中的常量,只需按名称使用它:

<script type="text/javascript">
    alert(constants.T_URL);
</script>
Run Code Online (Sandbox Code Playgroud)


Jay*_*Jay 5

您可以使用 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());
    }
Run Code Online (Sandbox Code Playgroud)