Share constants between C# and Javascript in MVC Razor

前端 未结 4 1030
一个人的身影
一个人的身影 2020-12-02 08:36

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
{
             


        
4条回答
  •  误落风尘
    2020-12-02 09:12

    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:

    
    

    Now whenever you need a constant in your scripts simply use it by name:

    
    

提交回复
热议问题