mercredi 6 avril 2016

Retrieve model name in custom display name attribute

Here is my development requirement,

My label values are stored in the database, and I still want to use the data annotation in a declarative way, this is to make my model more readable.

And here is my approach,

I decided to write custom DisplayNameAttribute, where the default value provided by my model will be overwritten by the value retrieved from the database.

Here is the property defined in the model,

    [CustomDisplay(Name: "First Name")]
    [CustomRequired(ErrorMessage: "{0} is required")]
    public String FirstName { get; set; }

Here is the custom display name attribute class,

public class CustomDisplayAttribute : DisplayNameAttribute
{
    private string _defaultName;
    private string _displayName;

    public CustomDisplayAttribute(string Name)
    {
        _defaultName = Name;
    }

    public override string DisplayName
    {
        get
        {
            if (String.IsNullOrEmpty(_displayName))
            {
                _displayName = DAO.RetrieveValue(**ModelName**, _defaultName);
            }
            return _displayName;
        }
    }
}

Now, you can see in the above code, ModelName is something I need it, which I don't have!!

While debugging, I dig in to ModelMetadataProviders.Current and can see the availability of the current model in action. But, as it is part of non-public static members I am unable to access it through my code.

enter image description here

I don't want to use reflection, so can anyone help me with the standard way to access model name in my custom display name attribute.

Aucun commentaire:

Enregistrer un commentaire