数据注释在MVC,需要是不显示在按钮单击



我正在练习MVC Web Application . net Framework。我在这里感到困惑,因为我已经安装了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>
}

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

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

要使客户端验证工作,您需要jQuery, jQuery验证插件和jQuery Unobtrusive validation。您可以从CDN加载这三个文件,例如:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.11/jquery.validate.unobtrusive.min.js"></script>

你可以添加脚本引用到你的视图来测试它是否工作,但通常你会添加jQuery到_Layout。cshtml和其他两个到一个名为_ValidationScriptsPartial.cshtml的部分视图。如果您使用最新的项目模板,这是默认配置。

查看此处所需的配置:https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-5.0

相关内容

  • 没有找到相关文章

最新更新