繁体   English   中英

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

[英]How to display enum attribute in Engine.Razor.RunCompile method

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

 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);

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM