【发布时间】:2011-05-17 09:27:41
【问题描述】:
我的模型看起来像这样:
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; }
}
还有一个如下所示的创建视图:
<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>
在Application_Start() 方法中,我将DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes 设置为false。
MaxStudents 可以为空且不需要,但是,如果MaxStudents 为空,则Modelstate 无效(ModelState.IsValid = false)。
我的错误消息没有显示,而是我得到的错误消息是A value is required。
我该怎么做才能让ModelState.IsValid 成为真实的?
【问题讨论】:
-
我刚刚将 MaxStudents 设置为可为空的 int 并且效果很好。但我仍然很好奇为什么我的 ModelState 无效
标签: jquery-validate asp.net-mvc-3