我的团队正在使用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; }
}
提前谢谢!
答案 0 :(得分:2)
我不认为这是做事的好方法。通常,使用元数据类是一种设计气味。我最近转向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;
}
}