0

I would like to write a custom attribute that I can decorate a ViewModel property with such that, when the ViewModel is posted I can check to see which of the posted properties has this attribute and run some logic. I am trying to set conditions, and this should not affect validation in any way.

[SetsCondition(SomeEnumerationValue)]
public Fund SelectedFund {get;set;}
...
other properties

then in the controller.

[HttpPost]
public IActionResult SelectFund(SelectFundViewModel model){
   if(ModelState.IsValid){
      //check which properties have the SetsCondition Attribute
      //read the SomeEnumerationValue for them
      ..
      //profit
   }
}

just not quite sure what sort of attribute I should be inheriting from, or for that matter, how to check if a particular ViewModel property is decorated with one.

any help much appreciated

nat
  • 2,185
  • 5
  • 32
  • 64

2 Answers2

2

You can create attribute from inheriting from Attribute:

[System.AttributeUsage(System.AttributeTargets.Property)]
public class ConditionAttribute : System.Attribute
{
    public readonly string value;
    public ConditionAttribute(string value)
    {
        this.value = value;
    }
}

Usage

[Condition("Some Value")]
public bool Property { get; set; }

You can then access this information through reflection: The below example is take from the link provided above:

System.Reflection.MemberInfo info = typeof(MyClass);
object[] attributes = info.GetCustomAttributes(true);
for (int i = 0; i < attributes.Length; i ++)
{
    System.Console.WriteLine(attributes[i]);
}

Updated link https://learn.microsoft.com/en-us/dotnet/csharp/tutorials/attributes

Scrobi
  • 1,215
  • 10
  • 13
0

Must inherit from System.ComponentModel.DataAnnotations.ValidationAttribute, and must implement the isValid method. Check https://stackoverflow.com/a/11959931/1270813 for an example

jparaya
  • 1,331
  • 11
  • 15