繁体   English   中英

如何获得资源的价值? (超过 1 种语言)

[英]How to get the values of the resources? (More than 1 languages)

我只需要资源的值。 我尝试过这种方式。 因为我有这个代码。 但是为什么property的属性总是null呢? 我认为该属性是 DisplayName。

我错了什么? 有没有更好的方法来获取资源的价值? 不使用 Model? (它是电子邮件内容的一部分。)

在 Controller

    private string DisplayName(string value)
    {
      try
      {
         PropertyInfo property = typeof(FormModel).GetProperty(value);
         var attribute = property.GetCustomAttribute(typeof(DisplayNameAttribute), true).Cast<DisplayNameAttribute>().FirstOrDefault();
    
         if (attribute == null)
           return value;
        else
           return attribute.DisplayName;
      }
      catch (Exception ex)
      {
          return value;
       }
    }
    
    private string GetHtmlContent(Dto dto)
    {
        string htmlContent = string.Empty;
    
        htmlContent += $"<h4>{DisplayName("PersonalData")</h4>";
        enz...
    }

Model:

public class FormModel
{
    [Display(Name = "PersonalData", ResourceType = typeof(StringResource))]
    public string PersonalData { get; set; }

    [Display(Name = "Name", ResourceType = typeof(StringResource))]
    public string Name { get; set; }

    [Display(Name = "Phone", ResourceType = typeof(StringResource))]
    public string Phone { get; set; }

    [Display(Name = "EMail", ResourceType = typeof(StringResource))]
    public string EMail { get; set; }

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

解决此异常的简单方法也许将DisplayNameAttribute更改为DisplayAttribute

var attribute = property.GetCustomAttribute(typeof(DisplayAttribute), true).Cast<DisplayAttribute>().FirstOrDefault();

但这不是制作多语言 web 网站的好方法

看到这个链接

暂无
暂无

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

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