I have model that looks like this:
public class Lesson
{
public int Id { get; set; }
[Required(ErrorMessage = "Naam voor de les is verplicht")]
[Display(Name="Naam")]
public string Name { get; set; }
[Required(ErrorMessage = "Tijd is verplicht")]
[Display(Name="Tijd")]
public string Time { get; set; }
//Prijs is default exclusief BTW
[Required(ErrorMessage = "Prijs is verplicht")]
[Display(Name="Prijs (excl btw)")]
public double Price { get; set; }
[Display(Name = "Maximum aantal leerlingen")]
public int MaxStudents { get; set; }
}
And a create view that looks like this:
<div>
<div>
@Html.LabelFor(model => model.Name)
</div>
<div>
@Html.TextBoxFor(model => model.Name, new { @class = "gt-form-text" })
@Html.ValidationMessageFor(model => model.Name)
</div>
<div>
@Html.LabelFor(model => model.Time)
</div>
<div>
@Html.TextBoxFor(model => model.Time, new { @class = "gt-form-text" })
@Html.ValidationMessageFor(model => model.Time)
</div>
<div>
@Html.LabelFor(model => model.Price)
</div>
<div>
@Html.TextBoxFor(model => model.Price, new { @class = "gt-form-text" })
@Html.ValidationMessageFor(model => model.Price)
</div>
<div>
@Html.LabelFor(model => model.MaxStudents)
</div>
<div>
@Html.TextBoxFor(model => model.MaxStudents,
new { @class = "gt-form-text" })
@Html.ValidationMessageFor(model => model.MaxStudents)
</div>
</div>
In the Application_Start() method I set DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes to false.
MaxStudents is nullable and not required, nevertheless, if MaxStudents is null, the Modelstate is not valid (ModelState.IsValid = false).
My errormessage is not shown, instead of that I get the errormessage is A value is required.
What can I do to get ModelState.IsValid to be true?
Someone shared this with me, and I’ll pass it on in case it helps. Sometimes those validation errors get swallowed up and are hard to find. When I was having a similar issue, I added this code to my ActionResult (HttpPost) and it got me right to the error in question.