三、实例演示
接下来我们来演示上面定义的两个验证特性在ASP.NET MVC项目中的应用。我们先定义如下一个实体类型Person,RequiredAttribute和RangeAttribute分别应用在表示名字、年龄和体重的Name、Age和Weight三个属性上。具体的验证规则是:名称是必需的,年龄必须大于18周岁而体重不得终于160斤。表示验证消息的ID和站位符对象数组作了相应的设置。
1: public class Person
2: {
3: [Required("RequiredField","Name")]
4: public string Name { get; set; }
5: [Range(18,int.MaxValue,"GreaterThan","Age",18)]
6: public int Age { get; set; }
7: [Range(int.MinValue, 160, "LessThan", "Weight", 160)]
8: public double Weight { get; set; }
9: }
2: {
3: [Required("RequiredField","Name")]
4: public string Name { get; set; }
5: [Range(18,int.MaxValue,"GreaterThan","Age",18)]
6: public int Age { get; set; }
7: [Range(int.MinValue, 160, "LessThan", "Weight", 160)]
8: public double Weight { get; set; }
9: }
在创建的ASP.NET MVC项目中添加下一个HomeController。
1: public class HomeController : Controller
2: {
3: public ActionResult Index()
4: {
5: return View(new Person { Name = "Zhan San", Age = 24, Weight = 120 });
6: }
7:
8: [HttpPost]
9: public ActionResult Index(Person person)
10: {
11: if (this.ModelState.IsValid)
12: {
13: throw new NotImplementedException();
14: }
15: return View();
16: }
17: }
2: {
3: public ActionResult Index()
4: {
5: return View(new Person { Name = "Zhan San", Age = 24, Weight = 120 });
6: }
7:
8: [HttpPost]
9: public ActionResult Index(Person person)
10: {
11: if (this.ModelState.IsValid)
12: {
13: throw new NotImplementedException();
14: }
15: return View();
16: }
17: }
Index.cshtml的内容如下所示,这是一个以Person对象作为Model的View。具体来说,这个View用于对Person对象三个属性的修改。
1: @model Artech.Web.Mvc.Extensions.Person
2:
3: @{
4: ViewBag.Title = "Index";
5: }
6:
7: <h2>Index</h2>
8: @using (Html.BeginForm())
9: { 10: @Html.EditorForModel()
11: <input type="submit" value="Save" />
12: }
2:
3: @{
4: ViewBag.Title = "Index";
5: }
6:
7: <h2>Index</h2>
8: @using (Html.BeginForm())
9: { 10: @Html.EditorForModel()
11: <input type="submit" value="Save" />
12: }
运行我们的程序,如果输入的内容不符合定义在Person类型上的验证规则,相应的验证消息会被现实,而这些消息都是通过MessageManager来获取的。