Question

I have a model I would like to use in a form using EditorForModel(). For all non-String data types (like bool, DateTime etc), the form created makes the fields required, even though I have not set the [Required} data annotation. How do I set the Object.cshtml file to recognize that this is not a required field?

Was it helpful?

Solution

It's not a "Required" problem, it's the base ModelBinding comportement : non nullable types cannot be null in the DefaultModelBinder. If ModelBinding fails, Model.IsValid = false => display this kind of errors.

You wouldn't have an "error" message with a bool? (which is nullable) or with a string (same), but you'll have with a bool (which isn't).

(it's basic "strong type logic" : try to write DateTime dt = null in c#...)

So one solution could be to create a new ModelBinder (saying all "null" bool are set to false, for example). But I'm really not sure that's what you need. The default behavior is generally fine

I just give you an example of CustomModelBinder : we use it to avoid having to type 0 values in most of our numeric fields : it's set value to 0 when no value has been typed in field with Int32, UInt32 and double values

public class AcceptNullAsZeroModelBinder : DefaultModelBinder
    {
        protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, object value)
        {
            if (value == null && (
                propertyDescriptor.PropertyType == typeof(Int32) ||
                propertyDescriptor.PropertyType == typeof(UInt32) ||
                propertyDescriptor.PropertyType == typeof(double)
                ))
            {
                base.SetProperty(controllerContext, bindingContext, propertyDescriptor, 0);
                return;
            }

            base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top