始终显示验证错误 [英] Validation errors are always displayed

查看:66
本文介绍了始终显示验证错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个MVC 5应用程序.我正在尝试使用我的viewmodel属性应用验证.例如.我的字段是必填字段.但是由于某种原因,在用户可以输入任何内容之前,最初会在空白字段上显示错误.你能解释一下吗?

I have an MVC 5 application. I am trying to apply validation using my viewmodel attributes. E.g. my fields are required. But for some reason, errors on empty fields are displayed initially, before the user can enter anything. Could you please explain?

@Html.ValidationSummary(false, "Please fix the errors:", new { @class = "text-danger" })
<div class="form-group">
    @Html.LabelFor(model => model.FileToUpload, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.TextBox("FileToUpload", "", new { @type = "file", @class = "input-xlarge form-control" })
        @Html.ValidationMessageFor(model => model.FileToUpload, "*", new { @class = "text-danger" })
    </div>
</div>

...

public ActionResult Index()
{
    return View();
}

我仅将我的视图模型用于验证目的,因此它不会传递给视图.

I use my viewmodel only for validation purposes, so it is not passed to the view.

推荐答案

正如我所评论的,一种解决方案是添加以下CSS:

As I have commented one solution is to add the following css:

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

但是另一种方法是检查视图中是否有错误,然后显示:

But another way is to check if there are errors in your view then display:

@if (ViewData.ModelState.Any(x => x.Value.Errors.Any()))
{
    @Html.ValidationSummary(false, "Please fix the errors:", new { @class = "text-danger" })    
}

这篇关于始终显示验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆