feat : AddChapter + EditChapter
continuous-integration/drone/push Build is passing Details

pages_listes
Yvan CALATAYUD 1 year ago
parent 85ea42f958
commit a88dfa6fc9

@ -3,7 +3,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17 # Visual Studio Version 17
VisualStudioVersion = 17.8.34330.188 VisualStudioVersion = 17.8.34330.188
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Blazor", "Blazor\Blazor.csproj", "{F9B19564-ED8F-49F7-97D7-2132F92DE3C2}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Blazor", "Blazor\Blazor.csproj", "{F9B19564-ED8F-49F7-97D7-2132F92DE3C2}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution

@ -0,0 +1,13 @@
using System.ComponentModel.DataAnnotations;
namespace Blazor.Models
{
public class ChapterModel
{
public int Id { get; set; }
[Required(ErrorMessage = "Name is required")]
[StringLength(50, ErrorMessage = "Name is too long.")]
public string Name { get; set; }
}
}

@ -0,0 +1,20 @@
@page "/addChapter"
@using Blazor.Models
<h3>Add Chapter</h3>
<EditForm Model="@chapterModel" OnValidSubmit="@HandleValidSubmit">
<DataAnnotationsValidator />
<ValidationSummary />
<p>
<label for="name">
Name:
<InputText id="name" @bind-Value="chapterModel.Name" />
</label>
</p>
<button type="submit">Submit</button>
</EditForm>

@ -0,0 +1,28 @@
using Blazored.LocalStorage;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Components;
using Blazor.Models;
using Blazor.Services;
namespace Blazor.Pages
{
public partial class AddChapter
{
private ChapterModel chapterModel = new();
[Inject]
public IDataService DataService { get; set; }
[Inject]
public NavigationManager NavigationManager { get; set; }
private async void HandleValidSubmit()
{
await DataService.Add(chapterModel);
NavigationManager.NavigateTo("chapters");
}
}
}

@ -3,6 +3,12 @@
@using Blazorise.DataGrid @using Blazorise.DataGrid
<h3>Chapters</h3> <h3>Chapters</h3>
<div>
<NavLink class="btn btn-primary" href="addChapter" Match="NavLinkMatch.All">
<i class="fa fa-plus"></i> Ajouter
</NavLink>
</div>
<DataGrid TItem="Chapter" <DataGrid TItem="Chapter"
Data="@chapters" Data="@chapters"
ReadData="@OnReadData" ReadData="@OnReadData"
@ -12,5 +18,10 @@
Responsive> Responsive>
<DataGridColumn TItem="Chapter" Field="@nameof(Chapter.Id)" Caption="#" /> <DataGridColumn TItem="Chapter" Field="@nameof(Chapter.Id)" Caption="#" />
<DataGridColumn TItem="Chapter" Field="@nameof(Chapter.Name)" Caption="Display name" /> <DataGridColumn TItem="Chapter" Field="@nameof(Chapter.Name)" Caption="Display name" />
<DataGridColumn TItem="Chapter" Field="@nameof(Chapter.Id)" Caption="Action">
<DisplayTemplate>
<a href="editChapter/@(context.Id)" class="btn btn-primary"><i class="fa fa-edit"></i> Editer</a>
</DisplayTemplate>
</DataGridColumn>
</DataGrid> </DataGrid>

@ -1,6 +1,9 @@
using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components;
using Blazor.Models; using Blazor.Models;
using Blazorise.DataGrid; using Blazorise.DataGrid;
using Blazored.LocalStorage;
using Blazorise;
using Blazor.Services;
namespace Blazor.Pages namespace Blazor.Pages
{ {
@ -11,10 +14,10 @@ namespace Blazor.Pages
private int totalItem; private int totalItem;
[Inject] [Inject]
public HttpClient Http { get; set; } public IDataService DataService { get; set; }
[Inject] [Inject]
public NavigationManager NavigationManager { get; set; } public IWebHostEnvironment WebHostEnvironment { get; set; }
private async Task OnReadData(DataGridReadDataEventArgs<Chapter> e) private async Task OnReadData(DataGridReadDataEventArgs<Chapter> e)
{ {
@ -23,14 +26,10 @@ namespace Blazor.Pages
return; return;
} }
// When you use a real API, we use this follow code
//var response = await Http.GetJsonAsync<Item[]>( $"http://my-api/api/data?page={e.Page}&pageSize={e.PageSize}" );
var response = (await Http.GetFromJsonAsync<Chapter[]>($"{NavigationManager.BaseUri}fake-data.json")).Skip((e.Page - 1) * e.PageSize).Take(e.PageSize).ToList();
if (!e.CancellationToken.IsCancellationRequested) if (!e.CancellationToken.IsCancellationRequested)
{ {
totalItem = (await Http.GetFromJsonAsync<List<Chapter>>($"{NavigationManager.BaseUri}fake-data.json")).Count; chapters = await DataService.List(e.Page, e.PageSize);
chapters = new List<Chapter>(response); // an actual data for the current page totalItem = await DataService.Count();
} }
} }
} }

@ -0,0 +1,18 @@
@page "/editChapter/{Id:int}"
<h3>Edit Chapter</h3>
<EditForm Model="@chapterModel" OnValidSubmit="@HandleValidSubmit">
<DataAnnotationsValidator />
<ValidationSummary />
<p>
<label for="name">
Name:
<InputText id="name" @bind-Value="chapterModel.Name" />
</label>
</p>
<button type="submit">Submit</button>
</EditForm>

@ -0,0 +1,42 @@
using Blazor.Models;
using Blazor.Services;
using Microsoft.AspNetCore.Components;
namespace Blazor.Pages
{
public partial class EditChapter
{
[Parameter]
public int Id { get; set; }
private ChapterModel chapterModel = new();
[Inject]
public IDataService DataService { get; set; }
[Inject]
public NavigationManager NavigationManager { get; set; }
[Inject]
public IWebHostEnvironment WebHostEnvironment { get; set; }
protected override async Task OnInitializedAsync()
{
var chapter = await DataService.GetById(Id);
// Set the model with the chapter
chapterModel = new ChapterModel
{
Id = chapter.Id,
Name = chapter.Name
};
}
private async void HandleValidSubmit()
{
await DataService.Update(Id, chapterModel);
NavigationManager.NavigateTo("chapters");
}
}
}

@ -1,4 +1,5 @@
using Blazor.Data; using Blazor.Data;
using Blazor.Services;
using Blazored.LocalStorage; using Blazored.LocalStorage;
using Blazorise; using Blazorise;
using Blazorise.Bootstrap; using Blazorise.Bootstrap;
@ -22,6 +23,8 @@ builder.Services
builder.Services.AddBlazoredLocalStorage(); builder.Services.AddBlazoredLocalStorage();
builder.Services.AddScoped<IDataService, DataLocalService>();
var app = builder.Build(); var app = builder.Build();
// Configure the HTTP request pipeline. // Configure the HTTP request pipeline.

@ -0,0 +1,118 @@
using Blazor.Models;
using Blazored.LocalStorage;
using Microsoft.AspNetCore.Components;
namespace Blazor.Services
{
public class DataLocalService : IDataService
{
private readonly HttpClient _http;
private readonly ILocalStorageService _localStorage;
private readonly NavigationManager _navigationManager;
private readonly IWebHostEnvironment _webHostEnvironment;
public DataLocalService(
ILocalStorageService localStorage,
HttpClient http,
IWebHostEnvironment webHostEnvironment,
NavigationManager navigationManager)
{
_localStorage = localStorage;
_http = http;
_webHostEnvironment = webHostEnvironment;
_navigationManager = navigationManager;
}
public async Task<Chapter> GetById(int id)
{
// Get the current data
var currentData = await _localStorage.GetItemAsync<List<Chapter>>("data");
// Get the chapter int the list
var chapter = currentData.FirstOrDefault(w => w.Id == id);
// Check if chapter exist
if (chapter == null)
{
throw new Exception($"Unable to found the item with ID: {id}");
}
return chapter;
}
public async Task Update(int id, ChapterModel model)
{
// Get the current data
var currentData = await _localStorage.GetItemAsync<List<Chapter>>("data");
// Get the chapter int the list
var chapter = currentData.FirstOrDefault(w => w.Id == id);
// Check if chapter exist
if (chapter == null)
{
throw new Exception($"Unable to found the item with ID: {id}");
}
// Modify the content of the chapter
chapter.Name = model.Name;
// Save the data
await _localStorage.SetItemAsync("data", currentData);
}
public async Task Add(ChapterModel model)
{
// Get the current data
var currentData = await _localStorage.GetItemAsync<List<Chapter>>("data");
// Simulate the Id
model.Id = currentData.Max(s => s.Id) + 1;
// Add the chapter to the current data
currentData.Add(new Chapter
{
Id = model.Id,
Name = model.Name
});
// Save the data
await _localStorage.SetItemAsync("data", currentData);
}
public async Task<int> Count()
{
// Load data from the local storage
var currentData = await _localStorage.GetItemAsync<Chapter[]>("data");
// Check if data exist in the local storage
if (currentData == null)
{
// this code add in the local storage the fake data
var originalData = await _http.GetFromJsonAsync<Chapter[]>($"{_navigationManager.BaseUri}fake-data.json");
await _localStorage.SetItemAsync("data", originalData);
}
return (await _localStorage.GetItemAsync<Chapter[]>("data")).Length;
}
public async Task<List<Chapter>> List(int currentPage, int pageSize)
{
// Load data from the local storage
var currentData = await _localStorage.GetItemAsync<Chapter[]>("data");
// Check if data exist in the local storage
if (currentData == null)
{
// this code add in the local storage the fake data
var originalData = await _http.GetFromJsonAsync<Chapter[]>($"{_navigationManager.BaseUri}fake-data.json");
await _localStorage.SetItemAsync("data", originalData);
}
return (await _localStorage.GetItemAsync<Chapter[]>("data")).Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
}
}
}

@ -0,0 +1,17 @@
using Blazor.Models;
namespace Blazor.Services
{
public interface IDataService
{
Task Add(ChapterModel model);
Task<int> Count();
Task<List<Chapter>> List(int currentPage, int pageSize);
Task<Chapter> GetById(int id);
Task Update(int id, ChapterModel model);
}
}
Loading…
Cancel
Save