There are certain properties in my application that I need to set dynamically whether they are required or not, therefore I can not use the [Required] atribute of Data Annotations.
Maybe this is not the best way to achieve what I want. So I will accept glady anny suggestions in that regard. I have overridden the DataAnnotationsModelMetadataProvider with:
public class DynamicFieldsMetadataProvider : DataAnnotationsModelMetadataProvider
{
public override IEnumerable<ModelMetadata> GetMetadataForProperties(object container, Type containerType)
{
if (containerType == null)
throw new ArgumentNullException("containerType");
if (!typeof(DynamicFieldDataItem).IsAssignableFrom(containerType))
foreach (var metadataProperty in base.GetMetadataForProperties(container, containerType))
yield return metadataProperty;
else
foreach (var metadataProperty in base.GetMetadataForProperties(container, containerType))
{
var dynamicField = (DynamicFieldDataItem)container;
if (metadataProperty.PropertyName == "DataFieldValue")
metadataProperty.IsRequired = dynamicField.IsRequired;
yield return metadataProperty;
}
}
}
This is just a concept test, once I make it work, I will change it to something dynamic and more object oriented, but so far, with just being able to set the MetadataModel for the property DataFieldValue to IsRequired = true I can get going.
With this I successfully set in a dynamic way the IsRequired property in true (I thought, with this would be enough!), and when I debugg in my view:
@Html.EditorFor(model=>model.DataFieldValue)
The property DataFieldValue is declared like this:
public class DynamicFieldDataItem
{
public string DataFieldValue { get; set; }
public bool IsRequired{ get; set; }
}
I can see that the Metadata, has the property IsRequired in true, but when the "DataFieldValue" is rendered the "validator" is not there, and of course the validation doesn't work.
To make sure that there wasn't a problem on the configuration of my project, I checked web.config and the inclusion of the javascripts for validation, all is properly configured. What's more, If I add the attribute Required to my property, like this:
public class DynamicFieldDataItem
{
[Required]
public string DataFieldValue { get; set; }
public bool IsRequired{ get; set; }
}
The validation works perfectly!
Can anyone give me a hint? Or tell me what i am doing wrong?
Thanks!