forked from rer-github/govuk-design-system-dotnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GovUkViewModel.cs
98 lines (83 loc) · 3.23 KB
/
GovUkViewModel.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using GovUkDesignSystem.Helpers;
using Microsoft.Extensions.Primitives;
namespace GovUkDesignSystem
{
public abstract class GovUkViewModel
{
private readonly Dictionary<string, string> errors = new Dictionary<string, string>();
private readonly Dictionary<string, StringValues> unparsedValues = new Dictionary<string, StringValues>();
private readonly HashSet<string> propertiesWithSuccessfullyParsedValues = new HashSet<string>();
internal void ValueWasSuccessfullyParsed(PropertyInfo property)
{
propertiesWithSuccessfullyParsedValues.Add(property.Name);
}
internal bool HasSuccessfullyParsedValue(PropertyInfo property)
{
return propertiesWithSuccessfullyParsedValues.Contains(property.Name);
}
internal void AddUnparsedValues(string parameterName, StringValues values)
{
unparsedValues.Add(parameterName, values);
}
internal bool HasUnparsedValues(string parameterName)
{
return unparsedValues.ContainsKey(parameterName);
}
internal StringValues GetUnparsedValues(string parameterName)
{
if (unparsedValues.ContainsKey(parameterName))
{
return unparsedValues[parameterName];
}
else
{
return StringValues.Empty;
}
}
public void AddErrorFor<TModel, TProperty>(
Expression<Func<TModel, TProperty>> propertyLambdaExpression, string errorMessage)
where TModel : GovUkViewModel
{
var property = ExpressionHelpers.GetPropertyFromExpression(propertyLambdaExpression);
AddErrorFor(property, errorMessage);
}
internal void AddErrorFor(PropertyInfo property, string errorMessage)
{
errors.Add(property.Name, errorMessage);
}
public bool HasErrorFor<TModel, TProperty>(
Expression<Func<TModel, TProperty>> propertyLambdaExpression)
where TModel : GovUkViewModel
{
var property = ExpressionHelpers.GetPropertyFromExpression(propertyLambdaExpression);
return HasErrorFor(property);
}
internal bool HasErrorFor(PropertyInfo property)
{
return errors.ContainsKey(property.Name);
}
public bool HasAnyErrors()
{
return errors.Count > 0;
}
internal Dictionary<string, string> GetAllErrors()
{
return errors;
}
public string GetErrorFor<TModel, TProperty>(
Expression<Func<TModel, TProperty>> propertyLambdaExpression)
where TModel : GovUkViewModel
{
var property = ExpressionHelpers.GetPropertyFromExpression(propertyLambdaExpression);
return GetErrorFor(property);
}
internal string GetErrorFor(PropertyInfo property)
{
return errors.ContainsKey(property.Name) ? errors[property.Name] : null;
}
}
}