如何在ASP.Net MVC 5中显示错误验证摘要标题

时间:2017-08-03 19:03:23

标签: c# asp.net asp.net-mvc validation asp.net-mvc-5

我是ASP.Net MVC 5的初学者,我想知道如何在页面顶部显示所有错误的验证摘要“标题消息”。

以下是我现在所拥有的:

查看:

@model WebApplication3.Models.Form
@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    <div class="form-horizontal">
        <h4>Form</h4>
        @* first parameter false means show all the errors *@
        @* second parameter means the message to display as Header on top*@
        @Html.ValidationSummary(false,"Fix below error", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "*", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.age, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.age, new { htmlAttributes = new { @class = "form-control" } })
                @*star meaning show the star sign to keep show field required.  *@
                @Html.ValidationMessageFor(model => model.age, "*", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

@* CLIENT SIDE VALIDATION*@
@section Scripts
 {
 @Scripts.Render("~/bundles/jqueryval")
 }

模型

 public class Form
    {
        public int Id { get; set; }
        [Required]
        public string Name { get; set; }
        [Required]
        [Remote("IsAgeUnique", "Form", ErrorMessage = "Age is not unique")]
        public int age { get; set; }
    }

P.S: 我已经为每个属性使用了@Html.ValidationMessageFor(prop, "*")通配符,以便在UI字段中显示星标消息。

问题: 当页面加载时,错误标题已经显示在页面上。功能明智一切都很好。但在初始页面加载期间,为什么“标题消息显示”

enter image description here

1 个答案:

答案 0 :(得分:2)

你可以尝试添加如下的css规则,使头部错误部分最初不可见。

验证摘要文本最初具有validation-summary-valid类。如果有一些错误,它会变成validation-summary-errors,所以你的初始值没有任何错误,我想你可以使用css规则

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