Asp.NET MVC - Validate a Model Outside of the Controller

后端 未结 4 1218
萌比男神i
萌比男神i 2021-02-04 08:03

I am building an ASP.NET MVC project and going for the following Architecture:

  • A Core project that has models, validation, dto, logic, etc.
  • <
4条回答
  •  误落风尘
    2021-02-04 08:51

    I consider your approach to be good. Mapping one set of models to another could bring some bugs.

    The code you are looking for is:

    using System.ComponentModel.DataAnnotations;
    
    var context = new ValidationContext(model, serviceProvider: null, items: null);
    var results = new List();
    var isValid = Validator.TryValidateObject(model, context, results);
    if (!isValid)
        throw new Exception("Model is not valid because " + string.Join(", ", results.Select( s => s.ErrorMessage).ToArray()));
    

    For details see http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.validationcontext.aspx or http://odetocode.com/blogs/scott/archive/2011/06/29/manual-validation-with-data-annotations.aspx

提交回复
热议问题