加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

MVC 3验证 – 仅在失去焦点或提交后显示错误消息?

发布时间:2020-12-16 09:22:25 所属栏目:asp.Net 来源:网络整理
导读:我已经使用DataAnnotations(必需,stringlength等)在我的MVC 3应用程序中设置了实体,并且MVC页面正确地显示了验证错误消息.但是,在用户有机会输入无效值之前,一旦页面加载到新表单上,就会显示错误消息. 几年前我使用过JQuery验证,并且只能在用户失去对某个字
我已经使用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.如果您粘贴控制器代码,这可能有助于我们更好地诊断它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读