我的团队正在使用MetadataType中的模型验证构建viewmodel.我的问题是我使用的是非MVC项目,我可以用它来验证模型吗?如果是的话,你能举个例子吗?
[MetadataType(typeof(PersonMetadata))] public class Person { public int ID { get; set; } public string Name { get; set; } } public class PersonMetadata { [StringLength(255,ErrorMessage="Name is required"),required] [DisplayName("Name")] public string Name { get; set; } }
先谢谢你!
解决方法
我不认为这是做事的好方法.通常,使用元数据类是一种设计气味.我最近转向
Fluent Validation for .NET,看起来很有前途,可以插入MVC,但不需要MVC.
所有这一切,它是可行的:
var person = new Person(); var controllerSlashValidator = new FakeControllerValidator(); ModelStateDictionary modelStateDictionary; bool isValid = controllerSlashValidator.Validate(person,out modelStateDictionary);
这段代码需要下面的FakeControllerValidator
public class FakeControllerValidator: Controller { public FakeControllerValidator() { this.ControllerContext = new ControllerContext(new RequestContext(new HttpContextWrapper(System.Web.HttpContext.Current),new RouteData()),this); } public bool Validate(object model,out ModelStateDictionary modelStateDictionary) { bool isValid = TryValidateModel(model); modelStateDictionary = ModelState; return isValid; } }