【问题标题】:MVC Razor Validation Errors showing on page load when no data has been posted未发布数据时在页面加载时显示 MVC Razor 验证错误
【发布时间】:2018-06-10 18:26:37
【问题描述】:

我在搞乱数据注释。当我单击链接转到页面时,正在显示验证消息,但我希望除非已发布数据,否则不会显示验证消息。

查看:

@Html.TextBoxFor(m => m.EmailAddress, new { @placeholder = "Enter Email", @class = "form-control" })
@Html.ValidationSummary(true, "Registration Failed. Check your credentials")
@Html.ValidationMessageFor(m => m.EmailAddress, "You must enter a valid Email Address.")

型号:

[Required(ErrorMessage = "Email is required")]
[DataType(DataType.EmailAddress)]
[EmailAddress]
[Display(Name = "Email Address: ")]
public string EmailAddress { get; set; }

控制器:

[HttpGet]
        public ActionResult AddUser()
        {
            return View();
        }

        [HttpPost]
        public ActionResult AddUser(UserCreateViewModel user)
        {
            if (ModelState.IsValid)
            {
                var success = UserRepository.AddUser(user);

                if (success)
                {
                    return View("Success");
                }
            }

            return View("AddUser");
        }

就像我说的,我的问题发生在 AddUser 视图的页面加载上。当我点击链接查看 AddUser 页面时,加载后会显示验证消息,但此时尚未发布任何数据且模型为空。

【问题讨论】:

    标签: c# asp.net-mvc razor data-annotations asp.net-mvc-validation


    【解决方案1】:

    绑定用户后可以清除模型状态:

    ModelState.Clear();
    

    发生这种情况是因为ModelBinder 将在绑定时设置ModelState。 在绑定模型并返回具有相同模型的视图的每个操作中,您都会遇到此问题。

    [HttpPost]
    public ActionResult AddUser(UserCreateViewModel user)
    {
        if (ModelState.IsValid)
        {
            var success = UserRepository.AddUser(user);
    
            if (success)
            {
                return View("Success");
            }
        }
    
        ModelState.Clear(); // <-------
        return View("AddUser");
    }
    

    【讨论】:

    • 这对我真的很有帮助。我添加了 ModelState.Clear() 它隐藏了!!
    • 好朋友(y)
    • 值得一提的是,如果操作接收到带有数据注释的对象(而不是具有与所需属性相对应的参数或完全不同的类 w/ o 数据注释)
    • 当控制器 GET 动作有参数时,它似乎也会发生,与模型中的属性同名
    【解决方案2】:

    将验证样式设置为:

    .validation-summary-valid { display:none; }
    

    所以默认情况下它是隐藏的。错误将触发它显示。

    【讨论】:

    • 我使用的是自定义 CSS 文件,并且已停止包含旧的 Site.css 重新包含此(已通过您的上述修复)解决了我的问题。
    • 为什么我们需要手动操作。为什么它不由框架本身处理。 :-|
    • 这很可能是因为默认的 Site.css 已更改或丢失。
    【解决方案3】:
    .field-validation-valid {
      display: none;
    }
    

    只要在页面加载时触发验证,这个“.field-validation-valid”值就会自动添加到触发输入元素的类属性中。

    通过添加 CSS 以显示 none 作为该特定类的值,您将不再在初始页面加载时看到验证消息。

    在触摸特定输入元素后,验证消息仍将正常显示。

    【讨论】:

    • 想解释一下这如何回答 OP 的问题?
    • 这对 OP 没有帮助,但对我有帮助。非常感谢!
    • 我也是。非常感谢
    【解决方案4】:

    $('.field-validation-error').html("");

    【讨论】:

      猜你喜欢
      • 2017-10-21
      • 1970-01-01
      • 1970-01-01
      • 2015-04-09
      • 2018-02-18
      • 1970-01-01
      • 1970-01-01
      • 2021-02-22
      • 2014-11-15
      相关资源
      最近更新 更多