-
-
Notifications
You must be signed in to change notification settings - Fork 315
Expand file tree
/
Copy pathAddEditModal.razor.cs
More file actions
92 lines (79 loc) · 2.91 KB
/
AddEditModal.razor.cs
File metadata and controls
92 lines (79 loc) · 2.91 KB
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
using System.ComponentModel.DataAnnotations;
using FSH.BlazorWebAssembly.Client.Components.Common;
using FSH.BlazorWebAssembly.Client.Shared;
using Microsoft.AspNetCore.Components;
using MudBlazor;
namespace FSH.BlazorWebAssembly.Client.Components.EntityTable;
public partial class AddEditModal<TRequest> : IAddEditModal<TRequest>
{
[Parameter]
[EditorRequired]
public RenderFragment<TRequest> EditFormContent { get; set; } = default!;
[Parameter]
[EditorRequired]
public TRequest RequestModel { get; set; } = default!;
[Parameter]
[EditorRequired]
public Func<TRequest, Task> SaveFunc { get; set; } = default!;
[Parameter]
public Func<Task>? OnInitializedFunc { get; set; }
[Parameter]
[EditorRequired]
public string EntityName { get; set; } = default!;
[Parameter]
public object? Id { get; set; }
[CascadingParameter]
private MudDialogInstance MudDialog { get; set; } = default!;
private CustomValidation? _customValidation;
public bool IsCreate => Id is null;
[Parameter]
public bool HideId { get; set; }
public void ForceRender() => StateHasChanged();
// This should not be necessary anymore, except maybe in the case when the
// UpdateEntityRequest has different validation rules than the CreateEntityRequest.
// If that would happen a lot we can still change the design so this method doesn't need to be called manually.
public bool Validate(object request)
{
var results = new List<ValidationResult>();
if (!Validator.TryValidateObject(request, new ValidationContext(request), results, true))
{
// Convert results to errors
var errors = new Dictionary<string, ICollection<string>>();
foreach (var result in results
.Where(r => !string.IsNullOrWhiteSpace(r.ErrorMessage)))
{
foreach (string field in result.MemberNames)
{
if (errors.ContainsKey(field))
{
errors[field].Add(result.ErrorMessage!);
}
else
{
errors.Add(field, new List<string>() { result.ErrorMessage! });
}
}
}
_customValidation?.DisplayErrors(errors);
return false;
}
return true;
}
protected override Task OnInitializedAsync() =>
OnInitializedFunc is not null
? OnInitializedFunc()
: Task.CompletedTask;
private async Task SaveAsync()
{
if (await ApiHelper.ExecuteCallGuardedAsync(
() => SaveFunc(RequestModel),
Snackbar,
_customValidation,
$"{EntityName} {(IsCreate ? L["Created"] : L["Updated"])}."))
{
MudDialog.Close();
}
}
private void Cancel() =>
MudDialog.Cancel();
}