用mvc自带的验证的时候,添加验证的同一字段(Email)在两个视图中用,一个视图需要验证,一个不需要,怎么

Model层

   [DisplayName("用户邮箱")]
        [Required(AllowEmptyStrings = false, ErrorMessage = "邮箱不能为空")]
        [RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}",             ErrorMessage = "{0}的格式不正确")]
        [DataType(DataType.EmailAddress)]
        [Remote("CheckEmail","User",ErrorMessage="此邮箱已经被注册")]
        public string Email
        {
            set { _email = value; }
            get { return _email; }
        }
        /// <summary>
        /// 确认邮箱
        /// </summary>
        [Display(Name="确认邮箱")]
        [Compare("Email", ErrorMessage = "邮箱必须一致")]
        public virtual string EmailConfirm
        {
            get;
            set;
        }

 

view1(注册页)  
        <div class="editor-label">
            @Html.LabelFor(model => model.Email)
        </div>
        <div class="indent">
            @Html.EditorFor(model => model.Email)
        
         @Html.ValidationMessageFor(model => model.Email)
        </div>

view2(找回密码)

        <div class="editor-label">             @Html.LabelFor(model => model.Email)         </div>        

       <div class="indent">             @Html.EditorFor(model => model.Email)

        </div>      

       <div class="editor-label">             @Html.LabelFor(model => model.EmailConfirm)         </div>   

       <div class="indent">             @Html.EditorFor(model => model.EmailConfirm)                   @Html.ValidationMessageFor(model => model.EmailConfirm)         </div>

 <p>
       <input name="submit" type="submit" value="下一步" />
       </p>

当我点击提交的时候,view2不能提交,我发现这个和Email验证有关,因为这个视图的Emailconfirm要用到验证,而Email字段不需要,老是不能提交,怎么解决,请大侠帮忙,提前感谢!

饮歌长啸
浏览 648回答 4
4回答

皈依舞

1、自定义验证 2、创建两套 Model 模板

qq_遁去的一_1

@Html.ValidationMessageFor(model => model.EmailConfirm)    删掉

Smart猫小萌

两个ViewModel不就可以了吗

潇潇雨雨

一般都是使用两个ViewModel的
打开App,查看更多内容
随时随地看视频慕课网APP