Blazor right slide panel using Fluent UI Library

Esma 20 Reputation points
2024-05-31T11:00:04.6933333+00:00

Hello,

I have implemented a right-side sliding panel using the Fluent UI library. When I click on the cards the edit panel opens directly. However, I am encountering an issue where the data inside the edit panel does not load it opens empty. The data saves to the database correctly when I edit and save it, but I want to see the previously entered data when the edit panel is opened.

How can I achieve this

Thank you for your help.

@page "/EditWorkPanel/{Id:int}"
@using BlazorApp4.Data.Entity
@using Microsoft.AspNetCore.Components
@using Microsoft.FluentUI.AspNetCore.Components
@implements IDialogContentComponent<TaskModel>

<FluentDialogBody>
    <EditForm Model="@Content" OnValidSubmit="@HandleValidSubmit">
        <DataAnnotationsValidator />
        <FluentValidationSummary />
        @if (!string.IsNullOrEmpty(errorMessage))
        {
            <FluentMessageBar MessageBarType="MessageBarType.Error">
                @errorMessage
            </FluentMessageBar>
        }
        <div>
            <FluentCombobox Id="combobox-with-long-list" Autocomplete="ComboboxAutocomplete.Both" @bind-Value="SelectedDeveloper" TOption="string" Label="İlgilenen" Height="250px">
                <FluentOption Value="">--</FluentOption>
                @foreach (var developer in DeveloperNames)
                {
                    <FluentOption Value="@developer">@developer</FluentOption>
                }
            </FluentCombobox>
            <FluentValidationMessage For="@(() => SelectedDeveloper)" />
        </div>

        <div>
            <FluentDatePicker @bind-Value="Content.PlannedDate" Label="Planlanan Tarih" />
            <FluentValidationMessage For="@(() => Content.PlannedDate)" />
        </div>

        <div>
            <FluentTextField @bind-Value="Content.Title" Label="Başlık" Required="true" />
            <FluentValidationMessage For="@(() => Content.Title)" />
        </div>

        <div>
            <FluentTextArea @bind-Value="Content.Explanation" Label="Açıklama" Required="true" />
            <FluentValidationMessage For="@(() => Content.Explanation)" />
        </div>

        <div>
            <FluentDatePicker @bind-Value="Content.StartDate" Label="Başlangıç Tarihi" />
            <FluentValidationMessage For="@(() => Content.StartDate)" />
        </div>

    </EditForm>
</FluentDialogBody>
<FluentDialogFooter>
    <FluentButton @onclick="HandleValidSubmit" Type="ButtonType.Submit">Kaydet</FluentButton>
    <FluentButton @onclick="ClosePanel">Vazgeç</FluentButton>
</FluentDialogFooter>

using BlazorApp4.Data;
using BlazorApp4.Data.Entity;
using BlazorApp4.Modals;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.EntityFrameworkCore;
using Microsoft.FluentUI.AspNetCore.Components;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using static BlazorApp4.Enums.EnumDeclarations;

namespace BlazorApp4.Components.Pages.Work
{
    public partial class EditWorkPanel : ComponentBase, IDialogContentComponent<TaskModel>
    {
        [Parameter]
        public TaskModel Content { get; set; } = new TaskModel();
        [CascadingParameter]
        public DialogParameters DialogParameters { get; set; } = default!;
        [CascadingParameter]
        public FluentDialog Dialog { get; set; } = default!;
        [Inject]
        public IDbContextFactory<BlazorAppDbContext> DbContextFactory { get; set; }
        private List<string> DeveloperNames = new List<string>();
        private Dictionary<string, int> DeveloperDictionary = new Dictionary<string, int>();
        private string SelectedDeveloper;
        private EditContext _editContext;
        private string errorMessage;

        protected override async Task OnInitializedAsync()
        {
            await LoadDevelopers();

            if (Content != null && Content.Id > 0)
            {
                using var context = DbContextFactory.CreateDbContext();
                var task = await context.Works.SingleOrDefaultAsync(w => w.Id == Content.Id);

                if (task != null)
                {
                    Content.Title = task.Title;
                    Content.Explanation = task.Explanation;
                    Content.StatusID = task.StatusID;
                    Content.DeveloperID = task.DeveloperID;
                    Content.PlannedDate = task.PlannedDate;
                    Content.StartDate = task.StartDate;

                    SelectedDeveloper = DeveloperDictionary.FirstOrDefault(d => d.Value == Content.DeveloperID).Key;
                    _editContext = new EditContext(Content);
                }
            }

        }

        private async Task LoadDevelopers()
        {
            using var context = DbContextFactory.CreateDbContext();
            var developers = await context.Personal
                .Where(p => p.Roles == RolesEnum.Developer.ToString())
                .Select(p => new { p.Id, FullName = p.Name + " " + p.Surname })
                .ToListAsync();

            DeveloperNames = developers.Select(d => d.FullName).ToList();
            DeveloperDictionary = developers.ToDictionary(d => d.FullName, d => d.Id);
        }

        private async Task HandleValidSubmit()
        {
            errorMessage = string.Empty;

            if (_editContext.Validate())
            {
                if (string.IsNullOrEmpty(SelectedDeveloper) || string.IsNullOrEmpty(Content.Explanation) || string.IsNullOrEmpty(Content.Title))
                {
                    errorMessage = "Lütfen zorunlu olan alanları doldurunuz.";
                    return;
                }
                if (DeveloperDictionary.TryGetValue(SelectedDeveloper, out var DeveloperId))
                {
                    Content.DeveloperID = DeveloperId;
                    await Dialog.CloseAsync(DialogResult.Ok(Content));
                }
            }
            else
            {
                errorMessage = "Lütfen formdaki hataları düzeltiniz.";
            }
        }

        private async Task ClosePanel()
        {
            await Dialog.CloseAsync(DialogResult.Cancel());
        }
    }
}


@page "/Work/WorkList"
@using BlazorApp4.Data.Entity
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components
@using Microsoft.Extensions.Localization
@using Microsoft.FluentUI.AspNetCore.Components
@inject NavigationManager NavManager
@inject IDbContextFactory<BlazorAppDbContext> DbFactory
@inject IToastService ToastService
@inject IDialogService DialogService
@inject IStringLocalizer<Resource> Loc
@attribute [Authorize]
<FluentStack>
    <FluentLabel Typo="Typography.PaneHeader">
        İş Listesi
    </FluentLabel>
    <FluentSpacer />
    <FluentButton @onclick="OpenDialogAsync" Appearance="Appearance.Accent">
        Yeni İş Ekle
    </FluentButton>
</FluentStack>
<div class="board">
    @foreach (var status in Enum.GetValues(typeof(EnumDeclarations.WorkStatuses)).Cast<EnumDeclarations.WorkStatuses>())
    {
        <div class="column">
            <h3>@Loc["WorksEnum_" + status.ToString()]</h3>
            <div ondragover="event.preventDefault()" @ondrop="@(e => Drop(e, status))" class="dropzone">
                @foreach (var task in Tasks.Where(t => t.StatusID == (int)status))
                {
                    <FluentCard Id="@task.Id.ToString()" Draggable="true" @ondragstart="@(e => Drag(e, task))" @onclick="() => EditTask(task.Id)" class="card">
                        <h4>@task.Title</h4>
                        <p>@task.Explanation</p>
                    </FluentCard>
                }
            </div>
        </div>
    }
</div>
@code {
    private List<Works> Tasks = new List<Works>();
    private Works Payload;
    private IDialogReference? _dialog;
    protected override async Task OnInitializedAsync()
    {
        using var context = DbFactory.CreateDbContext();
        Tasks = await context.Works.ToListAsync();
    }
    //sürüklenen değeri saklar, sürükleme işlemi tamamlandığında kullanılır payload
    private void Drag(DragEventArgs e, Works task)
    {
        Payload = task;
    }
    //görevin bırakılma işlemi
    private async void Drop(DragEventArgs e, EnumDeclarations.WorkStatuses status)
    {
        //sürüklenen görevin durumunun yeniler
        if (Payload != null)
        {
            Payload.StatusID = (int)status;
            using var context = DbFactory.CreateDbContext();
            context.Works.Update(Payload);
            await context.SaveChangesAsync();
            Tasks = await context.Works.ToListAsync();
            StateHasChanged();
        }
    }
    private async Task OpenDialogAsync()
    {
        var parameters = new DialogParameters<Works>
            {
                Title = "Yeni İş Verisi Ekle"
            };
        var dialogReference = await DialogService.ShowDialogAsync<NewWorkDialog>(parameters);
        //dialogdan dönen veriyi temsil eder
        var result = await dialogReference.Result;
        //yeni bir iş eklemek için modal açar ve işler
        //yeni works nesnesi dönüyorsa
        if (result?.Data is Works newWork)
        {
            using var context = DbFactory.CreateDbContext();
            context.Works.Add(newWork);
            await context.SaveChangesAsync();
            Tasks.Add(newWork);
            StateHasChanged();
            ToastService.ShowSuccess("Yeni iş başarıyla eklendi.");
        }
    }
    private async Task EditTask(int taskId)
    {
        using var context = DbFactory.CreateDbContext();
        var task = await context.Works.SingleOrDefaultAsync(w => w.Id == taskId);
        if (task != null)
        {
            var viewModel = new TaskModel
                {
                    Id = task.Id,
                    Title = task.Title,
                    Explanation = task.Explanation,
                    StatusID = task.StatusID,
                    DeveloperID = task.DeveloperID,
                    CreateDate = task.CreateDate,
                    ModifyDate = task.ModifyDate,
                    PlannedDate = task.PlannedDate,
                    StartDate = task.StartDate,
                };
            var parameters = new DialogParameters<TaskModel>
                {
                    Title = "Düzenle",
                    Content = viewModel
                };
            _dialog = await DialogService.ShowPanelAsync<EditWorkPanel>(parameters);
            var result = await _dialog.Result;
            if (result?.Data is TaskModel editWork)
            {
                var existingWork = await context.Works.SingleOrDefaultAsync(w => w.Id == task.Id);
                if (existingWork != null)
                {
                    //değerlerin güncellenmesi
                    existingWork.Title = editWork.Title;
                    existingWork.Explanation = editWork.Explanation;
                    existingWork.StatusID = task.StatusID;
                    existingWork.DeveloperID = editWork.DeveloperID;
                    existingWork.ModifyDate = DateTime.Now;
                    existingWork.PlannedDate = editWork.PlannedDate;
                    existingWork.StartDate = editWork.StartDate;
                    context.Works.Update(existingWork);
                    await context.SaveChangesAsync();
                    Tasks = await context.Works.ToListAsync();
                    StateHasChanged();
                    ToastService.ShowSuccess("İş Başarıyla Güncellendi");
                }
            }
        }
    }
}

Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,595 questions
0 comments No comments
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.