我已经使用DataAnnotations(必需,stringlength等)在我的MVC 3应用程序中设置了实体,并且MVC页面正确地显示了验证错误消息.但是,在用户有机会输入无效值之前,一旦页面加载到新表单上,就会显示
几年前我使用过JQuery验证,并且只能在用户失去对某个字段的焦点或尝试提交表单后才显示错误消息.事实上,我认为这是默认行为.
反正在使用DataAnnotations在MVC 3中做同样的事情吗?
编辑:这是HTML
<div class="form horizontal floated w50p"> <h3>Billing Information</h3> @using(Html.BeginForm()){ <div class="item"> <div class="label"> <label>* First Name</label></div> <div class="value">@Html.TextBoxFor(x => x.Name)</div> <div class="value">@Html.ValidationMessageFor(x => x.Name)</div> </div> <div class="item"> <div class="label"> <label>* Address 1</label></div> <div class="value">@Html.TextBoxFor(x => x.Street1)</div> <div class="value">@Html.ValidationMessageFor(x => x.Street1)</div> </div> <div class="item"> <div class="label"> <label>Address 2</label></div> <div class="value">@Html.TextBoxFor(x => x.Street2)</div> </div> <div class="item"> <div class="label"> <label>Address 3</label></div> <div class="value">@Html.TextBoxFor(x => x.Street3)</div> </div> <div class="item"> <div class="label"> <label>City</label></div> <div class="value">@Html.TextBoxFor(x => x.City)</div> <div class="value">@Html.ValidationMessageFor(x => x.City)</div> </div> <div class="item"> <div class="label"> <label>State/Province/Region</label></div> <div class="value">@Html.TextBoxFor(x => x.StateProv)</div> <div class="value">@Html.ValidationMessageFor(x => x.StateProv)</div> </div> <div class="item"> <div class="label"> <label>Zip / Postal Code</label></div> <div class="value">@Html.TextBoxFor(x => x.PostalCode)</div> <div class="value">@Html.ValidationMessageFor(x => x.PostalCode)</div> </div> <div class="item"> <div class="label"> <label>* Contact Phone</label></div> <div class="value">@Html.TextBoxFor(x => x.ContactPhone)</div> <div class="value">@Html.ValidationMessageFor(x => x.ContactPhone)</div> </div> <input type="submit" value="Submit" /> }默认行为正是您所描述的(只有在字段失去焦点或表单提交后才会出现错误).因此,您的视图或控制器一定有问题.具体来说,它听起来像验证器认为用户即使在表单的第一个视图上也回发.表单的第一个视图应该是GET而不是POST.如果您粘贴控制器代码,这可能有助于我们更好地诊断它.