基于MetadataType ASP.Net C#验证模型 [英] ASP.Net C# validating model based on MetadataType
问题描述
我的团队建设与MetadataType内部模型验证的ViewModels。我的问题是,我使用一个非MVC项目,我可以用它来验证模型?如果是的话,可以请您举个例子?
My team is building ViewModels with model validation inside the MetadataType. My question is that I'm using a non-MVC project, can I use it to validate the model? If yes, can you please give an example?
[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; }
}
感谢你在前进!
推荐答案
我不认为这是做事情的好办法。一般情况下,使用元数据类是一个设计的气味。我最近开到流利验证了.NET ,这看起来非常有前途,是可插拔的MVC但并不要求MVC
I don't think this is a good way to do things. In general, using Metadata classes is a design smell. I was recently turned on to Fluent Validation for .NET, which looks very promising, is pluggable for MVC but does not require MVC.
之所以这么说,它是可行的:
All that being said, it is doable:
var person = new Person();
var controllerSlashValidator = new FakeControllerValidator();
ModelStateDictionary modelStateDictionary;
bool isValid = controllerSlashValidator.Validate(person,out modelStateDictionary);
这code将需要 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;
}
}
这篇关于基于MetadataType ASP.Net C#验证模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!