//Index Page (view) /Employee/Index
@model DataAnotaionExample.Models.Employee
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<form action="./Add">
Enter Name=@Html.TextBoxFor(m=>Model.Name)
@Html.ValidationMessageFor(m=>Model.Name)
<input type="submit" value="Submit" />
</form>
//雇员主管
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace DataAnotaionExample.Controllers
{
public class EmployeeController : Controller
{
// GET: Employee
public ActionResult Index()
{
return View();
}enter code here
}
}
Model类Employee.cs
namespace DataAnotaionExample.Models
{
public class Employee
{
[Required]
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
}
这是我的代码,如果我将“名称”字段保留为空白,则不会像需要该字段那样抛出错误。
此代码在Asp.Net MVC5框架中创建
答案 0 :(得分:1)
确保您已添加
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script
在布局页面的末尾:
答案 1 :(得分:0)
首先,您需要添加剃须刀
@model DataAnotaionExample.Models.Employee
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<form action="./Add">
//this one
@Html.ValidationSummary(true)
Enter Name=@Html.TextBoxFor(m=>Model.Name)
@Html.ValidationMessageFor(m=>Model.Name)
<input type="submit" value="Submit" />
</form>
然后,您应该在“ _Layout.cshtml”页面上喜欢这样的验证脚本
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
或者您可以在App_Start-> BundleConfig中使用此脚本
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js",
"~Scripts/jquery.validate.js",
"~/Scripts/jquery.validate.unobtrusive.js"
));
我希望这段代码对您有用。