I have a class Lets say
public class Customer { public int id; public string FirstName {get;set;} public string LastName {get;set;} public string JobName {get;set;} public double Salary {get;set;}
}
A grid shows all these customers on a page. However, depending on Customer selected say id=1 , I want FirstName to have a StringLengthAttribute in Validation Vs some other RegexAttribute/other CustomValidation Attribute or even same one with different value for customer id= 2
Can we inject the datannotations attribute dynamically to the model.
Below is what I was trying to do but does not seem to work.
public class CustomValidatorProvider : AssociatedValidatorProvider {
protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes)
{
if (context.HttpContext.Session["customerid"].ToString().Equals( "1"))
{
if (metadata != null && metadata.PropertyName != null && metadata.PropertyName.Equals("FirstName"))
{
StringLengthAttributeAdapter a = new StringLengthAttributeAdapter(metadata, context, new StringLengthAttribute(5));
yield return a;
}
}
if (context.HttpContext.Session["customerid"].ToString().Equals( "2"))
{
if (metadata != null && metadata.PropertyName != null && metadata.PropertyName.Equals("FirstName"))
{
StringLengthAttributeAdapter a = new StringLengthAttributeAdapter(metadata, context, new StringLengthAttribute(15));
yield return a;
}
}
}
}
and then register in global.asax as ModelValidatorProviders.Providers.Add(new CustomValidatorProvider());