开发者

ASP.Net C# validating model based on MetadataType

开发者 https://www.devze.com 2023-02-21 10:35 出处:网络
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 examp

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; }
 }

Thank you in advance!


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);

this code would need the FakeControllerValidator below

    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;
        }
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消