namespace LaaProduction.Web.Models { using System.Collections.Generic; using System.Web.Http.ModelBinding; public class ModelResult { private readonly Dictionary errors; private ModelResult(bool succeeded) { this.Succeeded = succeeded; this.errors = new Dictionary(); } private ModelResult(T value) { this.Succeeded = true; this.Value = value; } public T Value { get; } public bool Succeeded { get; } public IReadOnlyDictionary ModelErrors => this.errors; public void AddModelError(string key, string value) { if (key != null) { this.errors[key] = value; } } public static implicit operator ModelResult(T value) => new ModelResult(value); public static implicit operator ModelResult(KeyValuePair error) { var validationResults = new ModelResult(false); validationResults.AddModelError(error.Key, error.Value); return validationResults; } public static implicit operator ModelResult(ModelStateDictionary modelState) { var validationResults = new ModelResult(false); if (modelState != null) { foreach (var entry in modelState) { var errorKey = entry.Key; var errorValue = entry.Value; foreach (var error in errorValue.Errors) { if (!string.IsNullOrWhiteSpace(error.ErrorMessage)) { validationResults.AddModelError(errorKey, error.ErrorMessage); } } } } return validationResults; } } }