Share constants between C# and Javascript in MVC Razor

前端 未结 4 1033
一个人的身影
一个人的身影 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

    Rather then storing your constant data in a C# class, store it in a static config/constants file.

    // 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.

    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.

    jQuery.getJSON, JsonReaderWriterFactor

提交回复
热议问题