0

I want to add attributes to model class properties based on some conditions

example:

Suppose the following EmployeeModel Class:

public class EmployeeModel
{
    public int EmployeeId { get; set; }

    [Required]
    public string EmployeeName { get; set; }

}

I want to add the Required attribute on EmployeeName Based on Some Condition.

How can i implement that?

Amr Deif
  • 103
  • 1
  • 14
  • 2
    Use a [foolproof](http://foolproof.codeplex.com/) `[RequiredIf]` of similar conditional validation attribute –  Dec 13 '15 at 07:53
  • WOW that's an out of the box thinking. – Amr Deif Dec 13 '15 at 07:57
  • take a look... http://stackoverflow.com/questions/2417113/asp-net-mvc-conditional-validation – Mahedi Sabuj Dec 13 '15 at 07:59
  • Thanks – Stephen Muecke for your answer. I tried to implement RequiredIf but RequiredIf takes another dependent property and i want to implement some custom code. Somthing like that: [RequiredIfTrue(MyCustomClass.MyCustomeBoolMethod())] – Amr Deif Dec 13 '15 at 08:31
  • @AmrDeif, That's not possible. Just use a view model with a `boolean` property that you set in the controller based on `MyCustomeBoolMethod()` –  Dec 13 '15 at 09:26

1 Answers1

2

If you mean validation (Required also set the field as not null) you can implement a CustomValidationAttribute. The validation context calls IsValid of the attribute and there you can do every check you need. You can see an example directly from MSDN

https://msdn.microsoft.com/en-us/library/cc668224.aspx

bubi
  • 6,414
  • 3
  • 28
  • 45
  • Thanks for your reply. Actually the problem with this approach is that validation of EmployeeModel always occured on server after calling Post Action and exactly at the check (Model.IsValid) and that is not acceptable to me. I need validation to occur on clientside before reaching the post action. – Amr Deif Dec 13 '15 at 11:15
  • You can have the same custom validation in the client side as well!? A bit more explanation on what your client side is using would be helpful. – amuz Dec 13 '15 at 20:33
  • Thanks bubi and amuz, That was very helpful – Amr Deif Dec 16 '15 at 11:39