0

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.

Mindaugas
  • 163
  • 1
  • 7
  • 16

1 Answers1

0

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.

Ventsyslav Raikov
  • 6,882
  • 1
  • 25
  • 28
  • is it possible to get model object there somehow? – Mindaugas Jun 05 '12 at 11:53
  • as I said - no, and there is where?:) in the constructor? - as I said it will be invoked when you use reflection over the type of your model. If you badly need *any* object - just construct one using 'new' – Ventsyslav Raikov Jun 05 '12 at 12:14
  • that attribute can be used anywhere in any model. i dont need any object :) i need that one where PersonId is :). i mean is it possible to get model object anywhere in the attribute class :) – Mindaugas Jun 05 '12 at 12:26
  • well not 'automatically' - you should have constructed your model object elsewhere. You can define a property of the custom attribute of type PersonId and set it. – Ventsyslav Raikov Jun 05 '12 at 12:59
  • i dont need to have it automaticaly. :))) i need to get it in attribute class using reflection somehow. i know how to set it elsewhere. :) yes its constructed elsewhere at the moment :) can you give any code sample how to implement your last comment? – Mindaugas Jun 05 '12 at 13:39