How to access other Model field in custom Model field attribute?

314 views Asked by At

The problem is what i'm trying to create a custom Model field attribute in asp.net mvc3 what needs to access other model field. Named for example "PersonId".

So i have a model like this

public class PersonWoundModel : IAppointmentModel
    {

        public int PersonId { get; set; }

        [CustomAttribute("PersonId")]
        public FillInList Positions { get; set; }
}

and i have custom attribute

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
    public class CustomAttribute : Attribute, IMetadataAware
    {
        public int PersonId { get; private set; }


        public CustomAttribute(bool allowDelete, bool allowEdit, string htmlHelpers)
        {
           //i need to get a PersonId here somehow.. reflection or any other method.
        }
}

so basicaly i need to get aPersonId field in [CustomAttribute] for further usage. i was thinkin about using reflection but have no idea how to get a model object there. thanksa lot for any help guys.

1

There are 1 answers

5
Ventsyslav Raikov On

You cannot - because there is no model object.

Your attribute is 'serialized' in metadata - i.e. the fields needed to construct it are serialized so they have to be compile time known literals. The constructor will be called when you use reflection on your model class by using a method like GetCustomAttributes. But at that point you(in your code) will probably have some object to deal with.