74 lines
2.0 KiB
C#
74 lines
2.0 KiB
C#
namespace LaaProduction.Web.Models
|
|
{
|
|
using System.Collections.Generic;
|
|
using System.Web.Http.ModelBinding;
|
|
|
|
public class ModelResult<T>
|
|
{
|
|
private readonly Dictionary<string, string> errors;
|
|
|
|
private ModelResult(bool succeeded)
|
|
{
|
|
this.Succeeded = succeeded;
|
|
this.errors = new Dictionary<string, string>();
|
|
}
|
|
|
|
private ModelResult(T value)
|
|
{
|
|
this.Succeeded = true;
|
|
this.Value = value;
|
|
}
|
|
|
|
public T Value { get; }
|
|
|
|
public bool Succeeded { get; }
|
|
|
|
public IReadOnlyDictionary<string, string> ModelErrors
|
|
=> this.errors;
|
|
|
|
public void AddModelError(string key, string value)
|
|
{
|
|
if (key != null)
|
|
{
|
|
this.errors[key] = value;
|
|
}
|
|
}
|
|
|
|
public static implicit operator ModelResult<T>(T value)
|
|
=> new ModelResult<T>(value);
|
|
|
|
public static implicit operator ModelResult<T>(KeyValuePair<string, string> error)
|
|
{
|
|
var validationResults = new ModelResult<T>(false);
|
|
|
|
validationResults.AddModelError(error.Key, error.Value);
|
|
|
|
return validationResults;
|
|
}
|
|
|
|
public static implicit operator ModelResult<T>(ModelStateDictionary modelState)
|
|
{
|
|
var validationResults = new ModelResult<T>(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;
|
|
}
|
|
}
|
|
}
|