Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
738 views
in Technique[技术] by (71.8m points)

asp.net mvc 3 - Share constants between C# and Javascript in MVC Razor

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...