注意,现在该论坛控制器拥有两个Create()方法。其中,第一个Create()方法用于显示创建一个新的论坛消息的表单,当把表单数据寄送到服务器端时调用第二个Create()方法。
其中,第二个Create()方法利用了校验类对表单数据进行校验。如果校验失败,则重新显示Create视图。
最后,我们需要修改的是Message类。列表8中提供了修改过的Message类的完整代码。
列表8–Models\Message.cs
using System;
using MvcValidation;
namespace MvcForums.Models
{
public class Message
{
public Message()
{ }
public Message(int id, int? parentThreadId, int? parentMessageId, string author, string subject, string body)
{
this.Id = id;
this.ParentThreadId = parentThreadId;
this.ParentMessageId = parentMessageId;
this.Author = author;
this.Subject = subject;
this.Body = body;
}
public int Id { get; set; }
public int? ParentThreadId { get; set; }
public int? ParentMessageId { get; set; }
public string Author { get; set; }
[RequiredValidator("You must enter a message subject.")]
public string Subject { get; set; }
[RequiredValidator("You must enter a message body.")]
public string Body { get; set; }
public DateTime EntryDate { get; set; }
}
}
using MvcValidation;
namespace MvcForums.Models
{
public class Message
{
public Message()
{ }
public Message(int id, int? parentThreadId, int? parentMessageId, string author, string subject, string body)
{
this.Id = id;
this.ParentThreadId = parentThreadId;
this.ParentMessageId = parentMessageId;
this.Author = author;
this.Subject = subject;
this.Body = body;
}
public int Id { get; set; }
public int? ParentThreadId { get; set; }
public int? ParentMessageId { get; set; }
public string Author { get; set; }
[RequiredValidator("You must enter a message subject.")]
public string Subject { get; set; }
[RequiredValidator("You must enter a message body.")]
public string Body { get; set; }
public DateTime EntryDate { get; set; }
}
}
注意,两个RequiredValidator属性已经被添加到列表8中的Message类中。但是,对该类并没作其它的改变。
对论坛应用程序作以上所有的这些修改后,新的校验单元测试已能够顺利通过。至此,我们已经成功地把校验器添加到论坛应用程序中。
五、 总结
在本篇中,我们将已经成功地把基本的表单校验支持添加到此论坛应用程序上。我们创建了一组校验属性,它们可以应用于我们的模型类上。最后请注意在本篇中,我们实现的是基于服务器端的校验逻辑。在本系列的下一篇中,我想重点讨论如何解决客户端校验逻辑的问题。