Good day!
I’ve a model that is binded from JSON request, say like this:
public class MyModel
{
public bool isSomeFeatureEnabled { get; set; }
}
And controller like this:
public ActionResult Submit(MyModel request)
{
if (ModelState.IsValid)
{
..
}
else
{
..
}
}
When I post empty JSON object to this action ({}) it will be valid with isSomeFeatureEnabled=false. But I want this field ‘required’ in terms that it should be set always in particular value (true\false).
I can make this field nullable and put [Required] on it, but the field is not really nullable per model logic.
The same story with int, double and DateTime fields.
I use ASP.NET MVC 3 and default setting of:
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = true
Shouldn’t it work for this situation?
I think making this field nullable and also making it
Requiredis the best shot for now. As the book states, . Otherwise, you can write your own attribute, make the validate method return false when passed invalue = default(T)