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?
I have a model I would like to use in a form using EditorForModel()
Share
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 astring(same), but you’ll have with abool(which isn’t).(it’s basic “strong type logic” : try to write
DateTime dt = nullin 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