Dynamically change data annotation in dynamic data project

[亡魂溺海] 提交于 2019-12-04 06:05:35
phil soady

Generally speaking no, the attributes are compiled and become part of the CIL metadata. To investigate this is a good SO thread that goes into some detail on this topic. Is it possible to modify the attribute of a property at runtime?

Personally i think you should be looking at another way to pass the label to the front-end so you can be flexible. eg a Model that contains labels and values.

We've had a similar issue not long ago for using translations for our backend settings page and logs in the client's language.

Since we're already used to using and implementing .po translation library for use with POEdit software, we've chosen to go that way.

Our properties mostly already had custom attrubutes called DisplayName", which we used to show the title on a user control. We changed those to TranslatableDisplayName attributes, and made a public override to .toString() method in it, returning translation of the field called "translationKey", which was set in attributes constructor.

We then added search pattern "TranslatableDisplayName:1" to the .po translation file, resulting in all of our english display names being used and listed as translation keys in the po file. Just send these POs to translate its english word/sentence to specific language and youre good to go. Turned out super simple and useful.

Attribute example:

public class TranslatableDisplayName: Attribute
{
    private string translationKey = string.Empty;
    public TranslatableDisplayName(string translationKey)
    {
        this.translationKey = translationKey;
    } 

    public override string toString()
    {
        return Languages.getString(translationKey);
    } 
} 

Languages is a gnugettext Translation c# Library in our case, but can be any way of handling your attribute's return. Just call your database query, if you want. You need to have it as a static method though, unless you feed it via your static attribute's property or method on creation of your software, but before you first need it. Hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!