如何在Engine.Razor.RunCompile方法中显示枚举属性

时间:2018-01-12 22:19:30

标签: c# razor enums

我有一个模型,它定义了一些枚举属性。 这是其中之一

 public enum NutritionalRequirementValue
{
    Regular,
    [EnumMember(Value = "Mechanicla Soft")]
    Mechanicla_Soft,
    [EnumMember(Value = "Heart Healthy")]
    Heart_Healthy,
    [EnumMember(Value = "Low Cholesterol")]
    Low_Cholesterol,
    [EnumMember(Value = "Low Fat")]
    Low_Fat,
    [EnumMember(Value = "Sodium Restriction")]
    Sodium_Restriction,
    [EnumMember(Value = "No Added Salt")]
    No_Added_Salt,
    [EnumMember(Value = "Calorie ADA Diet")]
    Calorie_ADA_Diet,
    [EnumMember(Value = "No Concentrated Sweets")]
    No_Concentrated_Sweets,
    [EnumMember(Value = "Coumadin Diet")]
    Coumadin_Diet,
    [EnumMember(Value = "Renal Diet")]
    Renal_Diet,
    [EnumMember(Value = "Enteral Nutrition")]
    Enteral_Nutrition,
    TPN,
    Supplements,
    [EnumMember(Value = "Fluid Restriction")]
    Fluid_Restriction,
    other
}  

我想要做的是使用Razor引擎通过传递cshtml文件路径和模型来生成html。我正在使用这种方法来做到这一点

   private static readonly HashSet<string> RazorCache = new HashSet<string>();
    private static readonly string BaseDirectory = HttpRuntime.AppDomainAppPath;
    public static string Render<T>(T viewModel, string cshtmlFile)
    {
        cshtmlFile = Path.Combine(BaseDirectory, cshtmlFile);
        if (!File.Exists(cshtmlFile))
        {
            throw new ArgumentException(string.Format("The given cshtml file '{0}' must exist.", cshtmlFile));
        }
        var key = string.Format("key-{0}-{1}-{2}", cshtmlFile, File.GetLastWriteTimeUtc(cshtmlFile).Ticks, typeof(T));

        string result;
        if (!RazorCache.Contains(key))
        {
            var cshtml = File.ReadAllText(cshtmlFile);
            result = Engine.Razor.RunCompile(new LoadedTemplateSource(cshtml, cshtmlFile), key, typeof(T), viewModel);
            RazorCache.Add(key);
        }
        else
        {
            result = Engine.Razor.Run(key, typeof(T), viewModel);
        }
        return result;
    }

但是现在,生成的html具有枚举值,例如“Mechanicla_Soft”而不是“Mechanicla Soft”。这个下划线在前端是丑陋的。我的问题是如何获得“Mechanicla Soft”? 我尝试使用Jsonconvert用StringEnumConverter()序列化它,它在序列化的Json中很好,因为我可以看到值是“Mechanicla Soft”,但是一旦我将它反序列化回模型类型,它再次成为“Mechanicla_Soft”

 var modelStr = JsonConvert.SerializeObject(viewData, new Newtonsoft.Json.Converters.StringEnumConverter());
            var model = JsonConvert.DeserializeObject<PocViewData>(modelStr);

1 个答案:

答案 0 :(得分:0)

尝试像这样添加显示属性:

public enum  NutritionalRequirementValue
{
    Regular,
    [Display(Name = "Mechanicla Soft")]
    [EnumMember(Value = "Mechanicla Soft")]
    Mechanicla_Soft,
.......................
}