在MVC剃刀C#和Javascript之间共享常量 [英] Share constants between C# and Javascript in MVC Razor

查看:237
本文介绍了在MVC剃刀C#和Javascript之间共享常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想双方在服务器上,并在Javascript在客户端使用字符串常量,在C#。
我封装在C#类我常数

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";
     . . .
        }
}

我找到了一种方法来使用通过剃刀语法在Javascript这些常量,但看起来怪我:

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) { ... 

是否有共享C#和Javascript之间的常量更多的优雅的方式?
(或者至少更自动的,所以我没有做在两个文件中的变化)

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)

推荐答案

你正在使用它的方式是危险的。想象一下,你的一些常量包含报价,甚至更糟糕的其他一些危险字符=>这将打破你的JavaScript。

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.

我建议你写一个控制器的动作,这将成为所有常量,如JavaScript:

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>

这篇关于在MVC剃刀C#和Javascript之间共享常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆