Ich habe eine Seite, die ein Modell in OnParametersSet lädt. Dieses Modell kann in einem Formular bearbeitet werden. Dies funktioniert perfekt, wenn ich das Modell EditForm direkt über Model="ViewModel.Something"
. Ich kann es jedoch nicht mit EditContext zum Laufen bringen, da EditContext in OnParametersSet initialisiert werden möchte.
Unhandled exception rendering component: EditForm requires either a Model parameter, or an EditContext parameter, please provide one of these.
System.InvalidOperationException: EditForm requires either a Model parameter, or an EditContext parameter, please provide one of these.
at Microsoft.AspNetCore.Components.Forms.EditForm.OnParametersSet()
at Microsoft.AspNetCore.Components.ComponentBase.CallOnParametersSetAsync()
at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
Code:
@inject SomeViewModel ViewModel
@if(ViewModel.Something!= null)
{
<EditForm EditContext="editContext" OnValidSubmit="@Submit">
//...
</EditForm>
}
@code
{
[Parameter] public string? SomethingId { get; set; } = String.Empty;
private EditContext editContext { get; set; } = default!;
protected override void OnInitialized()
{
base.OnInitialized();
ViewModel.PropertyChanged += (o, e) => StateHasChanged();
ViewModel.LoadSomething.Subscribe(_ => editContext = new(ViewModel!.Something));
}
protected override void OnParametersSet()
{
base.OnParametersSet();
if(!string.IsNullOrEmpty(SomethingId))
{
ViewModel.Query = new LoadSomethingQuery(SomethingId);
}
}
//...
}
Ich möchte die IsModified-Eigenschaft von EditContext verwenden. Daher muss ich EditContext anstelle von Model verwenden. Aber es funktioniert nicht, wenn EditContext nach der Seiteninitialisierung initialisiert wird. Irgendeine Idee, wie man das löst?
Lösung des Problems
Eine Möglichkeit wäre, editContext auf Nullen zu prüfen:
@if(editContext!= null)
{
<EditForm EditContext="editContext" OnValidSubmit="@Submit">
//...
</EditForm>
}Eine weitere Option - Erstellen Sie den EditContext in ctor oder OnInitialized und ersetzen Sie ihn durch eine neue Instanz in OnParametesSet:
protected override void OnInitialized()
{
base.OnInitialized();
editContext = new EditContext(...);
...
}
protected override void OnParametersSet()
{
base.OnParametersSet();
if(!string.IsNullOrEmpty(SomethingId))
{
ViewModel.Query = new LoadSomethingQuery(SomethingId);
...
editContext = new EditContext(...);
}
}
Keine Kommentare:
Kommentar veröffentlichen