I have come across a scenerio that to customize DataAnnotations in Dynamic Data Web Application. This is the scenerio:
[Display(Name="DispName")]
public string DName{get;set;}
Instead of hardcoding Name="DispName" for Display DataAnnotation, I want to fetch some value from DataBase and fit int the Name attribute. like:
[Display(Name=SomeValueFromDB)]
public string DName{get;set;}
Is there any way to show the Name attribute of Display DataAnnotation from database instead of hardcoding its value?
Also how can I change the ScaffoldColumn(True/false) based on table values?
Can I do this using T4 template ?
Thanks in advance.
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.
来源:https://stackoverflow.com/questions/16644388/dynamically-change-data-annotation-in-dynamic-data-project