Avancée jusqu’à la partie edit et Creation of page editor

javascript_error
Thomas Chazot 2 years ago
parent fa2ab08281
commit 53d57c982b

@ -15,5 +15,9 @@
<ItemGroup> <ItemGroup>
<None Remove="Blazored.LocalStorage" /> <None Remove="Blazored.LocalStorage" />
<None Remove="Services\" />
</ItemGroup>
<ItemGroup>
<Folder Include="Services\" />
</ItemGroup> </ItemGroup>
</Project> </Project>

@ -1,5 +1,6 @@
using System; using System;
using BlazorApp.Models; using BlazorApp.Models;
using BlazorApp.Services;
using Blazored.LocalStorage; using Blazored.LocalStorage;
using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms; using Microsoft.AspNetCore.Components.Forms;
@ -17,6 +18,9 @@ namespace BlazorApp.Pages
[Inject] [Inject]
public NavigationManager NavigationManager { get; set; } public NavigationManager NavigationManager { get; set; }
[Inject]
public IDataService DataService { get; set; }
/// <summary> /// <summary>
/// The default enchant categories. /// The default enchant categories.
/// </summary> /// </summary>
@ -38,44 +42,8 @@ namespace BlazorApp.Pages
private async void HandleValidSubmit() private async void HandleValidSubmit()
{ {
// Get the current data await DataService.Add(itemModel);
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);
NavigationManager.NavigateTo("list");
NavigationManager.NavigateTo("list"); NavigationManager.NavigateTo("list");
} }

@ -0,0 +1,5 @@
@page "/edit/{Id:int}"
<h3>Edit</h3>
<div>My paremeter: @Id</div>

@ -0,0 +1,13 @@
using System;
using Microsoft.AspNetCore.Components;
namespace BlazorApp.Pages
{
public partial class Edit
{
[Parameter]
public int Id { get; set; }
}
}

@ -78,4 +78,9 @@
</DisplayTemplate> </DisplayTemplate>
</DataGridColumn> </DataGridColumn>
<DataGridColumn TItem="Item" Field="@nameof(Item.CreatedDate)" Caption="Created date" DisplayFormat="{0:d}" DisplayFormatProvider="@System.Globalization.CultureInfo.GetCultureInfo("fr-FR")" /> <DataGridColumn TItem="Item" Field="@nameof(Item.CreatedDate)" Caption="Created date" DisplayFormat="{0:d}" DisplayFormatProvider="@System.Globalization.CultureInfo.GetCultureInfo("fr-FR")" />
<DataGridColumn TItem="Item" Field="@nameof(Item.Id)" Caption="Action">
<DisplayTemplate>
<a href="Edit/@(context.Id)" class="btn btn-primary"><i class="fa fa-edit"></i> Editer</a>
</DisplayTemplate>
</DataGridColumn>
</DataGrid> </DataGrid>

@ -1,4 +1,5 @@
using BlazorApp.Models; using BlazorApp.Models;
using BlazorApp.Services;
using Blazored.LocalStorage; using Blazored.LocalStorage;
using Blazorise.DataGrid; using Blazorise.DataGrid;
using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components;
@ -23,6 +24,9 @@ namespace BlazorApp.Pages
[Inject] [Inject]
public IWebHostEnvironment WebHostEnvironment { get; set; } public IWebHostEnvironment WebHostEnvironment { get; set; }
[Inject]
public IDataService DataService { get; set; }
protected override async Task OnAfterRenderAsync(bool firstRender) protected override async Task OnAfterRenderAsync(bool firstRender)
{ {
// Do not treat this action if is not the first render // Do not treat this action if is not the first render
@ -49,14 +53,10 @@ namespace BlazorApp.Pages
return; return;
} }
// When you use a real API, we use this follow code
//var response = await Http.GetJsonAsync<Data[]>( $"http://my-api/api/data?page={e.Page}&pageSize={e.PageSize}" );
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 LocalStorage.GetItemAsync<List<Item>>("data")).Count; items = await DataService.List(e.Page, e.PageSize);
items = new List<Item>(response); // an actual data for the current page totalItem = await DataService.Count();
} }
} }
} }

@ -1,4 +1,5 @@
using BlazorApp.Data; using BlazorApp.Data;
using BlazorApp.Services;
using Blazored.LocalStorage; using Blazored.LocalStorage;
using Blazorise; using Blazorise;
using Blazorise.Bootstrap; using Blazorise.Bootstrap;
@ -20,6 +21,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,159 @@
using System;
using BlazorApp.Models;
using Blazored.LocalStorage;
using Microsoft.AspNetCore.Components;
namespace BlazorApp.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 Add(ItemModel model)
{
// Get the current data
var currentData = await _localStorage.GetItemAsync<List<Item>>("data");
// Simulate the Id
model.Id = currentData.Max(s => s.Id) + 1;
// Add the item to the current data
currentData.Add(new Item
{
Id = model.Id,
DisplayName = model.DisplayName,
Name = model.Name,
RepairWith = model.RepairWith,
EnchantCategories = model.EnchantCategories,
MaxDurability = model.MaxDurability,
StackSize = model.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}/{model.Name}.png");
// Write the file content
await File.WriteAllBytesAsync(fileName.FullName, model.ImageContent);
// Save the data
await _localStorage.SetItemAsync("data", currentData);
}
public async Task<int> Count()
{
return (await _localStorage.GetItemAsync<Item[]>("data")).Length;
}
public async Task<List<Item>> List(int currentPage, int pageSize)
{
// Load data from the local storage
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
var originalData = await _http.GetFromJsonAsync<Item[]>($"{_navigationManager.BaseUri}fake-data.json");
await _localStorage.SetItemAsync("data", originalData);
}
return (await _localStorage.GetItemAsync<Item[]>("data")).Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
}
public async Task<Item> GetById(int id)
{
// Get the current data
var currentData = await _localStorage.GetItemAsync<List<Item>>("data");
// Get the item int the list
var item = currentData.FirstOrDefault(w => w.Id == id);
// Check if item exist
if (item == null)
{
throw new Exception($"Unable to found the item with ID: {id}");
}
return item;
}
public async Task Update(int id, ItemModel model)
{
// Get the current data
var currentData = await _localStorage.GetItemAsync<List<Item>>("data");
// Get the item int the list
var item = currentData.FirstOrDefault(w => w.Id == id);
// Check if item exist
if (item == null)
{
throw new Exception($"Unable to found the item with ID: {id}");
}
// Save the image
var imagePathInfo = new DirectoryInfo($"{_webHostEnvironment.WebRootPath}/images");
// Check if the folder "images" exist
if (!imagePathInfo.Exists)
{
imagePathInfo.Create();
}
// Delete the previous image
if (item.Name != model.Name)
{
var oldFileName = new FileInfo($"{imagePathInfo}/{item.Name}.png");
if (oldFileName.Exists)
{
File.Delete(oldFileName.FullName);
}
}
// Determine the image name
var fileName = new FileInfo($"{imagePathInfo}/{model.Name}.png");
// Write the file content
await File.WriteAllBytesAsync(fileName.FullName, model.ImageContent);
// Modify the content of the item
item.DisplayName = model.DisplayName;
item.Name = model.Name;
item.RepairWith = model.RepairWith;
item.EnchantCategories = model.EnchantCategories;
item.MaxDurability = model.MaxDurability;
item.StackSize = model.StackSize;
item.UpdatedDate = DateTime.Now;
// Save the data
await _localStorage.SetItemAsync("data", currentData);
}
}
}

@ -0,0 +1,15 @@
using System;
using BlazorApp.Models;
namespace BlazorApp.Services
{
public interface IDataService
{
Task Add(ItemModel model);
Task<int> Count();
Task<List<Item>> List(int currentPage, int pageSize);
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 140 KiB

Loading…
Cancel
Save