首页 > 解决方案 > MVC 中的数据注释,按钮单击时未显示必需

问题描述

我正在练习 MVC Web Application .NET Framework。我在这里感到困惑,因为我已经安装了 Unobtusive.Validation 的 jQuery 库的 NuGet 包,但必填字段仍然不起作用。这是我的学生班

    {
        [Required (ErrorMessage ="Student Id is required")] 
        public int Id { get; set; }
        [Required(ErrorMessage = "Name is required")]
        public string  Name { get; set; }
        [Required(ErrorMessage = "Email is required")]
        public string Email { get; set; }
        [Required(ErrorMessage = "Contact is required")]
        public string Contact{ get; set; }
    }

这是StudentData.cshtml文件,其中结合了c#和Html的代码。


@{
    ViewBag.Title = "Student Data";
}

<h2>StudentData</h2>

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
<div class="form-horizontal">
    
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.Id, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Id, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Id, "", new { @class = "text-danger" })
        </div>
    </div>

    <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.Email, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Contact, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Contact, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Contact, "", new { @class = "text-danger" })
        </div>
    </div>

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

我该如何解决这个问题。我已经重新安装了 NuGet 包Unobtusive最新版本。

标签: c#htmlasp.netvisual-studiomodel-view-controller

解决方案


我以前也遇到过同样的问题。我认为程序的javascript文件相互冲突,最好检查如何引入项目javascript文件。


推荐阅读