Continuité du tutoriel

master
Johnny RATTON 1 year ago
parent 45d832b79f
commit d4421d6d7e

@ -7,6 +7,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Blazored.LocalStorage" Version="4.4.0" />
<PackageReference Include="Blazorise.Bootstrap" Version="1.3.3" /> <PackageReference Include="Blazorise.Bootstrap" Version="1.3.3" />
<PackageReference Include="Blazorise.DataGrid" Version="1.3.3" /> <PackageReference Include="Blazorise.DataGrid" Version="1.3.3" />
<PackageReference Include="Blazorise.Icons.FontAwesome" Version="1.3.3" /> <PackageReference Include="Blazorise.Icons.FontAwesome" Version="1.3.3" />
@ -21,4 +22,8 @@
</Compile> </Compile>
</ItemGroup> </ItemGroup>
<ItemGroup>
<Folder Include="wwwroot\images\" />
</ItemGroup>
</Project> </Project>

@ -0,0 +1,36 @@
using System.ComponentModel.DataAnnotations;
namespace BlazorProject.Models;
public class ItemModel
{
public int Id { get; set; }
[Required]
[StringLength(50, ErrorMessage = "Le nom affiché ne doit pas dépasser 50 caractères.")]
public string DisplayName { get; set; }
[Required]
[StringLength(50, ErrorMessage = "Le nom ne doit pas dépasser 50 caractères.")]
[RegularExpression(@"^[a-z''-'\s]{1,50}$", ErrorMessage = "Seulement les caractères en minuscule sont acceptées.")]
public string Name { get; set; }
[Required]
[Range(1, 64)]
public int StackSize { get; set; }
[Required]
[Range(1, 125)]
public int MaxDurability { get; set; }
public List<string> EnchantCategories { get; set; }
public List<string> RepairWith { get; set; }
[Required]
[Range(typeof(bool), "true", "true", ErrorMessage = "Vous devez accepter les conditions.")]
public bool AcceptCondition { get; set; }
[Required(ErrorMessage = "L'image de l'item est obligatoire !")]
public byte[] ImageContent { get; set; }
}

@ -0,0 +1,69 @@
@page "/add"
<h3>Add</h3>
<EditForm Model="@itemModel" OnValidSubmit="@HandleValidSubmit">
<DataAnnotationsValidator />
<ValidationSummary />
<p>
<label for="display-name">
Display name:
<InputText id="display-name" @bind-Value="itemModel.DisplayName" />
</label>
</p>
<p>
<label for="name">
Name:
<InputText id="name" @bind-Value="itemModel.Name" />
</label>
</p>
<p>
<label for="stack-size">
Stack size:
<InputNumber id="stack-size" @bind-Value="itemModel.StackSize" />
</label>
</p>
<p>
<label for="max-durability">
Max durability:
<InputNumber id="max-durability" @bind-Value="itemModel.MaxDurability" />
</label>
</p>
<p>
Enchant categories:
<div>
@foreach (var item in enchantCategories)
{
<label>
<input type="checkbox" @onchange="@(e => OnEnchantCategoriesChange(item, e.Value))" />@item
</label>
}
</div>
</p>
<p>
Repair with:
<div>
@foreach (var item in repairWith)
{
<label>
<input type="checkbox" @onchange="@(e => OnRepairWithChange(item, e.Value))" />@item
</label>
}
</div>
</p>
<p>
<label>
Item image:
<InputFile OnChange="@LoadImage" accept=".png" />
</label>
</p>
<p>
<label>
Accept Condition:
<InputCheckbox @bind-Value="itemModel.AcceptCondition" />
</label>
</p>
<button type="submit">Submit</button>
</EditForm>

@ -0,0 +1,125 @@
using Blazored.LocalStorage;
using BlazorProject.Models;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
namespace BlazorProject.Pages;
public partial class Add
{
[Inject]
public NavigationManager NavigationManager { get; set; }
[Inject]
public ILocalStorageService LocalStorage { get; set; }
[Inject]
public IWebAssemblyHostEnvironment WebHostEnvironment { get; set; }
/// <summary>
/// The default enchant categories.
/// </summary>
private List<string> enchantCategories = new List<string>() { "armor", "armor_head", "armor_chest", "weapon", "digger", "breakable", "vanishable" };
/// <summary>
/// The default repair with.
/// </summary>
private List<string> repairWith = new List<string>() { "oak_planks", "spruce_planks", "birch_planks", "jungle_planks", "acacia_planks", "dark_oak_planks", "crimson_planks", "warped_planks" };
/// <summary>
/// The current item model
/// </summary>
private ItemModel itemModel = new()
{
EnchantCategories = new List<string>(),
RepairWith = new List<string>()
};
private async void HandleValidSubmit()
{
// Get the current data
var currentData = await LocalStorage.GetItemAsync<List<Item>>("data");
// Simulate the Id
itemModel.Id = currentData.Max(s => s.Id) + 1;
// Add the item to the current data
currentData.Add(new Item
{
Id = itemModel.Id,
DisplayName = itemModel.DisplayName,
Name = itemModel.Name,
RepairWith = itemModel.RepairWith,
EnchantCategories = itemModel.EnchantCategories,
MaxDurability = itemModel.MaxDurability,
StackSize = itemModel.StackSize,
CreatedDate = DateTime.Now
});
// Save the image
var imagePathInfo = new DirectoryInfo($"{WebHostEnvironment.BaseAddress}/images");
// Check if the folder "images" exist
if (!imagePathInfo.Exists)
{
imagePathInfo.Create();
}
// Determine the image name
var fileName = new FileInfo($"{imagePathInfo}/{itemModel.Name}.png");
// Write the file content
await File.WriteAllBytesAsync(fileName.FullName, itemModel.ImageContent);
// Save the data
await LocalStorage.SetItemAsync("data", currentData);
NavigationManager.NavigateTo("List.razor");
}
private async Task LoadImage(InputFileChangeEventArgs e)
{
// Set the content of the image to the model
using (var memoryStream = new MemoryStream())
{
await e.File.OpenReadStream().CopyToAsync(memoryStream);
itemModel.ImageContent = memoryStream.ToArray();
}
}
private void OnEnchantCategoriesChange(string item, object checkedValue)
{
if ((bool)checkedValue)
{
if (!itemModel.EnchantCategories.Contains(item))
{
itemModel.EnchantCategories.Add(item);
}
return;
}
if (itemModel.EnchantCategories.Contains(item))
{
itemModel.EnchantCategories.Remove(item);
}
}
private void OnRepairWithChange(string item, object checkedValue)
{
if ((bool)checkedValue)
{
if (!itemModel.RepairWith.Contains(item))
{
itemModel.RepairWith.Add(item);
}
return;
}
if (itemModel.RepairWith.Contains(item))
{
itemModel.RepairWith.Remove(item);
}
}
}

@ -0,0 +1,4 @@
@page "/BlazorRoute"
@page "/DifferentBlazorRoute"
<h1>Blazor routing</h1>

@ -3,6 +3,11 @@
<h3>List</h3> <h3>List</h3>
<div>
<NavLink class="btn btn-primary" href="Add" Match="NavLinkMatch.All">
<i class="fa fa-plus"></i> Ajouter
</NavLink>
</div>
<DataGrid TItem="Item" <DataGrid TItem="Item"
Data="@items" Data="@items"
ReadData="@OnReadData" ReadData="@OnReadData"
@ -11,6 +16,18 @@
ShowPager ShowPager
Responsive> Responsive>
<DataGridColumn TItem="Item" Field="@nameof(Item.Id)" Caption="#" /> <DataGridColumn TItem="Item" Field="@nameof(Item.Id)" Caption="#" />
<DataGridColumn TItem="Item" Field="@nameof(Item.Id)" Caption="Image">
<DisplayTemplate>
@if (File.Exists($"{WebHostEnvironment.BaseAddress}/images/{context.Name}.png"))
{
<img src="images/@(context.Name).png" class="img-thumbnail" title="@context.DisplayName" alt="@context.DisplayName" style="max-width: 150px"/>
}
else
{
<img src="images/default.png" class="img-thumbnail" title="@context.DisplayName" alt="@context.DisplayName" style="max-width: 150px"/>
}
</DisplayTemplate>
</DataGridColumn>
<DataGridColumn TItem="Item" Field="@nameof(Item.DisplayName)" Caption="Display name" /> <DataGridColumn TItem="Item" Field="@nameof(Item.DisplayName)" Caption="Display name" />
<DataGridColumn TItem="Item" Field="@nameof(Item.StackSize)" Caption="Stack size" /> <DataGridColumn TItem="Item" Field="@nameof(Item.StackSize)" Caption="Stack size" />
<DataGridColumn TItem="Item" Field="@nameof(Item.MaxDurability)" Caption="Maximum durability" /> <DataGridColumn TItem="Item" Field="@nameof(Item.MaxDurability)" Caption="Maximum durability" />

@ -1,7 +1,9 @@
using System.Net.Http.Json; using System.Net.Http.Json;
using Blazored.LocalStorage;
using Blazorise.DataGrid; using Blazorise.DataGrid;
using BlazorProject.Models; using BlazorProject.Models;
using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
namespace BlazorProject.Pages; namespace BlazorProject.Pages;
@ -14,9 +16,34 @@ public partial class List
[Inject] [Inject]
public HttpClient Http { get; set; } public HttpClient Http { get; set; }
[Inject]
public ILocalStorageService LocalStorage { get; set; }
[Inject]
public IWebAssemblyHostEnvironment WebHostEnvironment { get; set; }
[Inject] [Inject]
public NavigationManager NavigationManager { get; set; } public NavigationManager NavigationManager { get; set; }
protected override async Task OnAfterRenderAsync(bool firstRender)
{
// Do not treat this action if is not the first render
if (!firstRender)
{
return;
}
var currentData = await LocalStorage.GetItemAsync<Item[]>("data");
// Check if data exist in the local storage
if (currentData == null)
{
// this code add in the local storage the fake data (we load the data sync for initialize the data before load the OnReadData method)
var originalData = await Http.GetFromJsonAsync<Item[]>($"{NavigationManager.BaseUri}sample-data/fake-data.json");
await LocalStorage.SetItemAsync("data", originalData);
}
}
private async Task OnReadData(DataGridReadDataEventArgs<Item> e) private async Task OnReadData(DataGridReadDataEventArgs<Item> e)
{ {
if (e.CancellationToken.IsCancellationRequested) if (e.CancellationToken.IsCancellationRequested)
@ -25,12 +52,12 @@ public partial class List
} }
// When you use a real API, we use this follow code // 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.GetJsonAsync<Data[]>( $"http://my-api/api/data?page={e.Page}&pageSize={e.PageSize}" );
var response = (await Http.GetFromJsonAsync<Item[]>($"{NavigationManager.BaseUri}sample-data/fake-data.json")).Skip((e.Page - 1) * e.PageSize).Take(e.PageSize).ToList(); var response = (await LocalStorage.GetItemAsync<Item[]>("data")).Skip((e.Page - 1) * e.PageSize).Take(e.PageSize).ToList();
if (!e.CancellationToken.IsCancellationRequested) if (!e.CancellationToken.IsCancellationRequested)
{ {
totalItem = (await Http.GetFromJsonAsync<List<Item>>($"{NavigationManager.BaseUri}sample-data/fake-data.json")).Count; totalItem = (await LocalStorage.GetItemAsync<List<Item>>("data")).Count;
items = new List<Item>(response); // an actual data for the current page items = new List<Item>(response); // an actual data for the current page
} }
} }

@ -1,3 +1,4 @@
using Blazored.LocalStorage;
using Blazorise; using Blazorise;
using Blazorise.Bootstrap; using Blazorise.Bootstrap;
using Blazorise.Icons.FontAwesome; using Blazorise.Icons.FontAwesome;
@ -7,6 +8,7 @@ using BlazorProject;
var builder = WebAssemblyHostBuilder.CreateDefault(args); var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.Services.AddBlazoredLocalStorage();
builder.Services builder.Services
.AddBlazorise() .AddBlazorise()
.AddBootstrapProviders() .AddBootstrapProviders()

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 220 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Loading…
Cancel
Save