Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customising data annotations in dynamic data

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?

Thanks in advance,

Sujith

like image 229
Sujith S Nair Avatar asked May 09 '13 07:05

Sujith S Nair


1 Answers

I found a solution. But this is applicable only if we build the application:

Create a custom class (Say: CustomDisplayNameAttribute ) which inherits DisplayNameAttribute. And call that class name as display attribute (here "CustomDisplayName") above the property name.

While setting DataAnnotation for Display attribute, omit that "Attribute" part from the class name. ie. the DataAnnotation for Display attribute will be CustomDisplayName (not CustomDisplayNameAttribute).

  public class DomainClass
{
    [CustomDisplayName("")]
    public object PropertyName{ get; set; }
}



public class CustomDisplayNameAttribute : DisplayNameAttribute
    {
        public CustomDisplayNameAttribute(string value)
            : base(GetMessageFromResource(value))
        { }

        private static string GetMessageFromResource(string value)
        {
            return "Custom Display Name";
        }
    }

Hope this helps all....

Happy Coding....

like image 192
Sujith S Nair Avatar answered Sep 27 '22 22:09

Sujith S Nair