@page "/settings/ingredients/edit" @page "/settings/ingredients/edit/{id}" @using CocktailWeb.Data @using Microsoft.AspNetCore.Components.Sections @using Microsoft.EntityFrameworkCore @using Microsoft.Extensions.Options @inject IDbContextFactory DataContextFactory; @inject NavigationManager nav; @inject IWebHostEnvironment env; @inject IOptions Config;
Alkoholisch
@if (curFlasche.ImageURL != null) { } else {
Kein Bild vorhanden
}
@code { [Parameter] public string? id { get; set; } public Flasche curFlasche = null!; public IBrowserFile? NewImage; private DbDataContext? _DataContext; protected override async Task OnInitializedAsync() { if (id != null) { _DataContext ??= await DataContextFactory.CreateDbContextAsync(); if (_DataContext != null) curFlasche = _DataContext.Flaschen.Single(f => f.Id == Convert.ToInt32(id)); } // Falls keine ID angegeben wurde oder der Eintrag in der Datenbank nicht gefunden wurde, gehen wir davon aus dass ein neuer Eintrag erstellt wird. if (curFlasche == null) curFlasche = new(); //await InvokeAsync(StateHasChanged); } public void Bild_OnChange(InputFileChangeEventArgs e) { NewImage = e.GetMultipleFiles().FirstOrDefault(); //this.StateHasChanged(); War in nem Stackexchange.. Nötig? } private async Task OnSubmit(EventArgs e) { _DataContext ??= await DataContextFactory.CreateDbContextAsync(); if (curFlasche != null && _DataContext != null) { if (id != null) { _DataContext.Flaschen.Update(curFlasche); } else { _DataContext.Flaschen.Add(curFlasche); } await _DataContext.SaveChangesAsync(); if (NewImage != null) { try { // Bild hochladen var relativeuploadpath = Path.Join(Config.Value.ImageUploadDir, $"ingredient_{curFlasche.Id}{Path.GetExtension(NewImage.Name)}"); var fullpath = Path.Join(env.WebRootPath, relativeuploadpath); string? folder = Path.GetDirectoryName(fullpath); if (folder != null && !Path.Exists(folder)) Directory.CreateDirectory(folder); Stream stream = NewImage.OpenReadStream(maxAllowedSize: Config.Value.MaxAllowedUploadSizeInMB * 1024 * 1024); FileStream fs = File.Create(fullpath); await stream.CopyToAsync(fs); stream.Close(); fs.Close(); curFlasche.ImageURL = relativeuploadpath; // URL hinterlegen und wieder speichern _DataContext.Flaschen.Update(curFlasche); await _DataContext.SaveChangesAsync(); } catch (Exception ex) { Console.WriteLine($"Error uploading image: {ex.Message}"); } } } nav.NavigateTo("/settings/ingredients"); } }