Création du formulaire

master
Dorian HODIN 2 years ago
parent d7753d3189
commit c543233c37

Binary file not shown.

@ -3,7 +3,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17 # Visual Studio Version 17
VisualStudioVersion = 17.4.33103.184 VisualStudioVersion = 17.4.33103.184
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProjetBlazor", "ProjetBlazor\ProjetBlazor.csproj", "{D63FE586-7854-4213-BB93-F39ABD37994C}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ProjetBlazor", "ProjetBlazor\ProjetBlazor.csproj", "{D63FE586-7854-4213-BB93-F39ABD37994C}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution

@ -7,8 +7,8 @@
public string? Name { get; set; } public string? Name { get; set; }
public int StackSize { get; set; } public int StackSize { get; set; }
public int MaxDurability { get; set; } public int MaxDurability { get; set; }
public List<string>? EnchantCategories { get; set; } public List<string> EnchantCategories { get; set; }
public List<string>? RepairWith { get; set; } public List<string> RepairWith { get; set; }
public DateTime CreatedDate { get; set; } public DateTime CreatedDate { get; set; }
public DateTime? UpdatedDate { get; set; } public DateTime? UpdatedDate { get; set; }
} }

@ -0,0 +1,38 @@
using System.ComponentModel.DataAnnotations;
namespace ProjetBlazor.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,40}$", 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,70 @@
@page "/add"
@using ProjetBlazor.Models;
<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,121 @@
using Blazored.LocalStorage;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Components;
using ProjetBlazor.Models;
namespace ProjetBlazor.Pages
{
public partial class Add
{
[Inject]
public ILocalStorageService LocalStorage { get; set; }
[Inject]
public IWebHostEnvironment 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.WebRootPath}/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);
}
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);
}
}
}
}

@ -3,6 +3,12 @@
<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 +17,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.WebRootPath}/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,4 +1,5 @@
using Blazorise.DataGrid; using Blazored.LocalStorage;
using Blazorise.DataGrid;
using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components;
using ProjetBlazor.Models; using ProjetBlazor.Models;
@ -11,10 +12,35 @@ namespace ProjetBlazor.Pages
private int totalItem; private int totalItem;
[Inject] [Inject]
public HttpClient? Http { get; set; } public HttpClient Http { get; set; }
[Inject] [Inject]
public NavigationManager? NavigationManager { get; set; } public ILocalStorageService LocalStorage { get; set; }
[Inject]
public IWebHostEnvironment WebHostEnvironment { get; set; }
[Inject]
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 = Http.GetFromJsonAsync<Item[]>($"{NavigationManager.BaseUri}fake-data.json").Result;
await LocalStorage.SetItemAsync("data", originalData);
}
}
private async Task OnReadData(DataGridReadDataEventArgs<Item> e) private async Task OnReadData(DataGridReadDataEventArgs<Item> e)
{ {
@ -24,12 +50,12 @@ namespace ProjetBlazor.Pages
} }
// 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}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}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,8 +1,7 @@
using Blazored.LocalStorage;
using Blazorise; using Blazorise;
using Blazorise.Bootstrap; using Blazorise.Bootstrap;
using Blazorise.Icons.FontAwesome; using Blazorise.Icons.FontAwesome;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using ProjetBlazor.Data; using ProjetBlazor.Data;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
@ -15,6 +14,7 @@ builder.Services.AddHttpClient();
builder.Services.AddBlazorise(); builder.Services.AddBlazorise();
builder.Services.AddBootstrapProviders(); builder.Services.AddBootstrapProviders();
builder.Services.AddFontAwesomeIcons(); builder.Services.AddFontAwesomeIcons();
builder.Services.AddBlazoredLocalStorage();
var app = builder.Build(); var app = builder.Build();

@ -7,6 +7,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Blazored.LocalStorage" Version="4.3.0" />
<PackageReference Include="Blazorise.Bootstrap" Version="1.1.3.1" /> <PackageReference Include="Blazorise.Bootstrap" Version="1.1.3.1" />
<PackageReference Include="Blazorise.Components" Version="1.1.3.1" /> <PackageReference Include="Blazorise.Components" Version="1.1.3.1" />
<PackageReference Include="Blazorise.DataGrid" Version="1.1.3.1" /> <PackageReference Include="Blazorise.DataGrid" Version="1.1.3.1" />

@ -1,4 +1,4 @@
y<div class="top-row ps-3 navbar navbar-dark"> <div class="top-row ps-3 navbar navbar-dark">
<div class="container-fluid"> <div class="container-fluid">
<a class="navbar-brand" href="">ProjetBlazor</a> <a class="navbar-brand" href="">ProjetBlazor</a>
<button title="Navigation menu" class="navbar-toggler" @onclick="ToggleNavMenu"> <button title="Navigation menu" class="navbar-toggler" @onclick="ToggleNavMenu">

@ -8,6 +8,7 @@
".NETCoreApp,Version=v6.0": { ".NETCoreApp,Version=v6.0": {
"ProjetBlazor/1.0.0": { "ProjetBlazor/1.0.0": {
"dependencies": { "dependencies": {
"Blazored.LocalStorage": "4.3.0",
"Blazorise.Bootstrap": "1.1.3.1", "Blazorise.Bootstrap": "1.1.3.1",
"Blazorise.Components": "1.1.3.1", "Blazorise.Components": "1.1.3.1",
"Blazorise.DataGrid": "1.1.3.1", "Blazorise.DataGrid": "1.1.3.1",
@ -18,6 +19,17 @@
"ProjetBlazor.dll": {} "ProjetBlazor.dll": {}
} }
}, },
"Blazored.LocalStorage/4.3.0": {
"dependencies": {
"Microsoft.AspNetCore.Components.Web": "6.0.9"
},
"runtime": {
"lib/net6.0/Blazored.LocalStorage.dll": {
"assemblyVersion": "1.0.0.0",
"fileVersion": "1.0.0.0"
}
}
},
"Blazorise/1.1.3.1": { "Blazorise/1.1.3.1": {
"dependencies": { "dependencies": {
"Microsoft.AspNetCore.Components": "6.0.9", "Microsoft.AspNetCore.Components": "6.0.9",
@ -213,6 +225,13 @@
"serviceable": false, "serviceable": false,
"sha512": "" "sha512": ""
}, },
"Blazored.LocalStorage/4.3.0": {
"type": "package",
"serviceable": true,
"sha512": "sha512-CfHp9SWN45cM/TM8uw4pELQBfCRtMssCMSOjsEXVWibeYBn36TLpzw+J1vsC2Su2BEQ3Et19A5+GqK1S3kHbTQ==",
"path": "blazored.localstorage/4.3.0",
"hashPath": "blazored.localstorage.4.3.0.nupkg.sha512"
},
"Blazorise/1.1.3.1": { "Blazorise/1.1.3.1": {
"type": "package", "type": "package",
"serviceable": true, "serviceable": true,

@ -20,6 +20,10 @@ build_property._RazorSourceGeneratorDebug =
build_metadata.AdditionalFiles.TargetPath = QXBwLnJhem9y build_metadata.AdditionalFiles.TargetPath = QXBwLnJhem9y
build_metadata.AdditionalFiles.CssScope = build_metadata.AdditionalFiles.CssScope =
[C:/Users/Dorian/Documents/Blazor/Code/ProjetBlazor/Pages/Add.razor]
build_metadata.AdditionalFiles.TargetPath = UGFnZXNcQWRkLnJhem9y
build_metadata.AdditionalFiles.CssScope =
[C:/Users/Dorian/Documents/Blazor/Code/ProjetBlazor/Pages/Counter.razor] [C:/Users/Dorian/Documents/Blazor/Code/ProjetBlazor/Pages/Counter.razor]
build_metadata.AdditionalFiles.TargetPath = UGFnZXNcQ291bnRlci5yYXpvcg== build_metadata.AdditionalFiles.TargetPath = UGFnZXNcQ291bnRlci5yYXpvcg==
build_metadata.AdditionalFiles.CssScope = build_metadata.AdditionalFiles.CssScope =

@ -1 +1 @@
4ca5aee22af6dc02a9d0273387223447bc3bf68a 3daeff49e80c57bfaf518ef6eb297e2f8cb35d56

@ -77,3 +77,4 @@ C:\Users\Dorian\Documents\Blazor\Code\ProjetBlazor\obj\Debug\net6.0\refint\Proje
C:\Users\Dorian\Documents\Blazor\Code\ProjetBlazor\obj\Debug\net6.0\ProjetBlazor.pdb C:\Users\Dorian\Documents\Blazor\Code\ProjetBlazor\obj\Debug\net6.0\ProjetBlazor.pdb
C:\Users\Dorian\Documents\Blazor\Code\ProjetBlazor\obj\Debug\net6.0\ProjetBlazor.genruntimeconfig.cache C:\Users\Dorian\Documents\Blazor\Code\ProjetBlazor\obj\Debug\net6.0\ProjetBlazor.genruntimeconfig.cache
C:\Users\Dorian\Documents\Blazor\Code\ProjetBlazor\obj\Debug\net6.0\ref\ProjetBlazor.dll C:\Users\Dorian\Documents\Blazor\Code\ProjetBlazor\obj\Debug\net6.0\ref\ProjetBlazor.dll
C:\Users\Dorian\Documents\Blazor\Code\ProjetBlazor\bin\Debug\net6.0\Blazored.LocalStorage.dll

File diff suppressed because one or more lines are too long

@ -44,6 +44,10 @@
"net6.0": { "net6.0": {
"targetAlias": "net6.0", "targetAlias": "net6.0",
"dependencies": { "dependencies": {
"Blazored.LocalStorage": {
"target": "Package",
"version": "[4.3.0, )"
},
"Blazorise.Bootstrap": { "Blazorise.Bootstrap": {
"target": "Package", "target": "Package",
"version": "[1.1.3.1, )" "version": "[1.1.3.1, )"

@ -2,6 +2,18 @@
"version": 3, "version": 3,
"targets": { "targets": {
"net6.0": { "net6.0": {
"Blazored.LocalStorage/4.3.0": {
"type": "package",
"dependencies": {
"Microsoft.AspNetCore.Components.Web": "6.0.0"
},
"compile": {
"lib/net6.0/Blazored.LocalStorage.dll": {}
},
"runtime": {
"lib/net6.0/Blazored.LocalStorage.dll": {}
}
},
"Blazorise/1.1.3.1": { "Blazorise/1.1.3.1": {
"type": "package", "type": "package",
"dependencies": { "dependencies": {
@ -358,6 +370,20 @@
} }
}, },
"libraries": { "libraries": {
"Blazored.LocalStorage/4.3.0": {
"sha512": "CfHp9SWN45cM/TM8uw4pELQBfCRtMssCMSOjsEXVWibeYBn36TLpzw+J1vsC2Su2BEQ3Et19A5+GqK1S3kHbTQ==",
"type": "package",
"path": "blazored.localstorage/4.3.0",
"files": [
".nupkg.metadata",
".signature.p7s",
"blazored.localstorage.4.3.0.nupkg.sha512",
"blazored.localstorage.nuspec",
"icon.png",
"lib/net6.0/Blazored.LocalStorage.dll",
"lib/net7.0/Blazored.LocalStorage.dll"
]
},
"Blazorise/1.1.3.1": { "Blazorise/1.1.3.1": {
"sha512": "HeCfUVSjWetHruRTj3oK9FVSN+i/HQ2sxNGdqVtWjvzqZKPS4QURI4ieee8HA2pYsPQjwMuBLA2GT39lCrMUHg==", "sha512": "HeCfUVSjWetHruRTj3oK9FVSN+i/HQ2sxNGdqVtWjvzqZKPS4QURI4ieee8HA2pYsPQjwMuBLA2GT39lCrMUHg==",
"type": "package", "type": "package",
@ -826,6 +852,7 @@
}, },
"projectFileDependencyGroups": { "projectFileDependencyGroups": {
"net6.0": [ "net6.0": [
"Blazored.LocalStorage >= 4.3.0",
"Blazorise.Bootstrap >= 1.1.3.1", "Blazorise.Bootstrap >= 1.1.3.1",
"Blazorise.Components >= 1.1.3.1", "Blazorise.Components >= 1.1.3.1",
"Blazorise.DataGrid >= 1.1.3.1", "Blazorise.DataGrid >= 1.1.3.1",
@ -877,6 +904,10 @@
"net6.0": { "net6.0": {
"targetAlias": "net6.0", "targetAlias": "net6.0",
"dependencies": { "dependencies": {
"Blazored.LocalStorage": {
"target": "Package",
"version": "[4.3.0, )"
},
"Blazorise.Bootstrap": { "Blazorise.Bootstrap": {
"target": "Package", "target": "Package",
"version": "[1.1.3.1, )" "version": "[1.1.3.1, )"

@ -1,9 +1,10 @@
{ {
"version": 2, "version": 2,
"dgSpecHash": "6hLYXK8WoTqhx1IwJA8PGbGU8ESmdGcxW9pjUr/cKHP4NiBOU8OrLHDJCDfhFvfwzpQwWwAxiqAmegegNU3rJw==", "dgSpecHash": "RWnGZpD9KZ48JOGf2jiZb2ZNQYIje5O3mkeeRYMJtyGXWyJ7NL9kHePDY71XGMyHut5RSweZbf7V6zkpiCLBOA==",
"success": true, "success": true,
"projectFilePath": "C:\\Users\\Dorian\\Documents\\Blazor\\Code\\ProjetBlazor\\ProjetBlazor.csproj", "projectFilePath": "C:\\Users\\Dorian\\Documents\\Blazor\\Code\\ProjetBlazor\\ProjetBlazor.csproj",
"expectedPackageFiles": [ "expectedPackageFiles": [
"C:\\Users\\Dorian\\.nuget\\packages\\blazored.localstorage\\4.3.0\\blazored.localstorage.4.3.0.nupkg.sha512",
"C:\\Users\\Dorian\\.nuget\\packages\\blazorise\\1.1.3.1\\blazorise.1.1.3.1.nupkg.sha512", "C:\\Users\\Dorian\\.nuget\\packages\\blazorise\\1.1.3.1\\blazorise.1.1.3.1.nupkg.sha512",
"C:\\Users\\Dorian\\.nuget\\packages\\blazorise.bootstrap\\1.1.3.1\\blazorise.bootstrap.1.1.3.1.nupkg.sha512", "C:\\Users\\Dorian\\.nuget\\packages\\blazorise.bootstrap\\1.1.3.1\\blazorise.bootstrap.1.1.3.1.nupkg.sha512",
"C:\\Users\\Dorian\\.nuget\\packages\\blazorise.components\\1.1.3.1\\blazorise.components.1.1.3.1.nupkg.sha512", "C:\\Users\\Dorian\\.nuget\\packages\\blazorise.components\\1.1.3.1\\blazorise.components.1.1.3.1.nupkg.sha512",

Loading…
Cancel
Save