ASP.Net C# validating model based on MetadataType

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!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x