When I submit a form with an empty string “for the Guid field, I get the error message“ MyGuid field is required. ”Although I did not set the Required attribute.
//NOT Required public Guid MyGuid { get; set; }
after binding the guid model is 00000000-0000-0000-0000-000000000000 (because it is the default value) and it is correct. But ModelState has the indicated error.
How to avoid this error?
Additional Information:
[Required(AllowEmptyStrings = true)] does not help
I do not want the directive to be null ( Guid? ), Because this would lead to many additional codes (checking if the value matters, the mapping, etc.)
Update:
OK, I realized that Guid? change Guid? in my view models does not result in many changes than I expected (some calls to MyGuid.GetValueOrDefault() or some checks for MyGuid.HasValue and calls MyGuid.Value ).
However, the reason that a model error is added if there is no valid Guid submitted a submit request is because DefaultModelBinder tries to bind null to Guid . The solution would be to override the DefaultModelBinder . And no errors will be added to the model state.
public class MyModelBinder : DefaultModelBinder { protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value) { if (propertyDescriptor.PropertyType == typeof(Guid) && value == null) { value = Guid.Empty; } base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value); } }
source share