【问题标题】:How to apply Culture on property level like DataAnotation in MVC not global level如何在属性级别应用文化,例如 MVC 中的数据注释而不是全局级别
【发布时间】:2016-11-05 08:47:12
【问题描述】:

我只需要在单个 TextBox 控件的 DataAnotation 属性中应用 Culture,而不是整个模型

语言https://msdn.microsoft.com/en-us/library/ee825488(v=cs.20).aspx

在 MVC5 C# 中

例如。

[System.ComponentModel.DataAnnotations.DisplayFormat(ApplyFormatInEditMode = true,DataFormatString = "ur-PK")]public string test { get; set; }

但它不起作用。

【问题讨论】:

  • 您的属性是string,将格式应用于string 是没有意义的!你想做什么?属性的值是多少,预期的输出是多少
  • 我正在尝试使用 URDU 语言输入支持来渲染文本框控件
  • 这不是 DisplayFormatAttribute 的用途 - 它用于以特定格式显示数字和 DateTime 属性 - 所以今天日期的 DateTime 可以显示为 11/5/2016 或 @ 987654329@等
  • 你能推荐任何其他数据类型吗
  • DataType 与语言输入支持无关。

标签: c# asp.net-mvc data-annotations culture


【解决方案1】:

如果您的问题是关于在特定文化中显示您的字符串并且您不想更改所有内容的语言(仅此文本框),您可以创建这样的自定义 DataAnnotation

public class LocalizedDisplayNameAttribute : DisplayNameAttribute
{
    public LocalizedDisplayNameAttribute(string displayNameKey)
        : base(displayNameKey)
    {
    }

    public override string DisplayName
    {
        get
        {
            // Get your string from db 
            // or load it from specific resource file 
            //(as your business) and return string;
        }
    }
}

但如果您不需要所有这些,您可以使用默认显示并从资源文件加载您的 sting

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    • 1970-01-01
    • 2018-03-02
    • 2021-09-11
    • 2019-11-20
    • 2010-12-24
    • 1970-01-01
    相关资源
    最近更新 更多