Share constants between C# and Javascript in MVC Razor

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

    You can use an HTML helper to output the script necessary, and use reflection to grab the fields and their values so it will automatically update.

        public static HtmlString GetConstants(this HtmlHelper helper)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
    
            sb.AppendLine("");
            return new HtmlString(sb.ToString());
        }
    

提交回复
热议问题