mare
mare

Reputation: 13083

Custom DataAnnotation attributes

When I use DisplayAttribute in ASP.NET MVC 3 models it quickly becomes a pain writing them because we have to either hardcode the string or reference the string from a some static class that contains const strings (which is what I have now, see below). But even that is too much for me.

I would like to come up with an attribute that would be called something like [SimpleDisplay] and it would implicitly construct the string for resources by looking at

  1. class name,
  2. property name that the attribute is attached to.

Is this possible?

Something like this

public class Product {

 [SimpleDisplay] // it will take Product and Name and do something like this Product_Name
 public string Name { get; set; } 

}

This is what I want to get rid of, if possible:

    [Display(ResourceType = typeof(Resources.Localize), Name = ResourceStrings.product_prettyid)]
    public virtual int PrettyId
    {
        get;
        set;
    }

    [Display(ResourceType = typeof(Resources.Localize), Name = ResourceStrings.product_name)]
    public virtual string Title
    {
        get;
        set;
    }

Now I know that it is not possible to inherit the DisplayAttribute cause it's sealed. What other options I have? Does it even make sense?

Upvotes: 2

Views: 5387

Answers (2)

Claus Trojahn
Claus Trojahn

Reputation: 80

If i have a correct understanding what you mean, you may just create a simple custom attribute like this one:

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

    public override string DisplayName {
        get {
            try {
                string[] vals = base.DisplayName.Split(',');
                if(vals != null && vals.Length == 2)
                    return (string)HttpContext.GetGlobalResourceObject(vals[0].Trim(), vals[1].Trim());
            } catch {}
            return "{res:" + base.DisplayName + "}";
        }
    }
}

You may then use it as an attribute on your properies. MVC HTML extensions will pickup your custom attribute.

[LocalizedDisplayName("LBL, lbl_name1")]
public string[] Name1 { get; set; }

Upvotes: 2

Jakub Konecki
Jakub Konecki

Reputation: 46008

I would try creating just a standard attribute and custom DataAnnotationsModelMetadataProvider. You can override CreateMetadata method, which gets IEnumerable<Attribute>. You should than search for your attribute

attributes.OfType<SimpleDisplayAttribute>().FirstOrDefault();

and populate model metadata in any way you want.

Upvotes: 5

Related Questions