travail sur la page de modification

blazor
Patrick BRUGIERE 1 year ago
parent ce2e96d4d1
commit 87f5360728

@ -8,9 +8,9 @@ namespace adminBlazor.Factories
{
public static class UserFactory
{
public static User ToModel(User user, byte[] imageContent)
public static UserModel ToModel(UserModel user, byte[] imageContent)
{
return new User
return new UserModel
{
Id = user.Id,
Name = user.Name,
@ -25,9 +25,9 @@ namespace adminBlazor.Factories
};
}
public static User Create(User user)
public static UserModel Create(UserModel user)
{
return new User
return new UserModel
{
Id = user.Id,
Name = user.Name,
@ -42,7 +42,7 @@ namespace adminBlazor.Factories
};
}
public static void Update(User item, User user)
public static void Update(UserModel item, UserModel user)
{
item.Id = user.Id;
item.Name = user.Name;

@ -4,36 +4,18 @@ namespace adminBlazor.Models
{
public class User
{
[Required]
public int Id { get; set; }
[StringLength(50, ErrorMessage = "Name length can't be more than 50.")]
[DataType(DataType.Password)]
[Required]
public string Password { get; set; }
[EmailAddress]
public string Email { get; set; }
[StringLength(50, ErrorMessage = "Name length can't be more than 50.")]
[Required]
public string Name { get; set; }
[StringLength(50, ErrorMessage = "Name length can't be more than 50.")]
public string Surname { get; set; }
[StringLength(50, ErrorMessage = "Name length can't be more than 50.")]
public string Nickname { get; set; }
[StringLength(50, ErrorMessage = "Name length can't be more than 50.")]
public string Image { get; set; }
public string Image { get; set; }
public bool ExtraTime { get; set; }
[Range(0,100)]
public int Group { get; set; }
[Range(0, 100)]
public int Group { get; set; }
public List<String> Roles { get; set; }
}
}

@ -0,0 +1,39 @@
using System.ComponentModel.DataAnnotations;
namespace adminBlazor.Models
{
public class UserModel
{
[Required]
public int Id { get; set; }
[StringLength(50, ErrorMessage = "Name length can't be more than 50.")]
[DataType(DataType.Password)]
[Required]
public string Password { get; set; }
[EmailAddress]
public string Email { get; set; }
[StringLength(50, ErrorMessage = "Name length can't be more than 50.")]
[Required]
public string Name { get; set; }
[StringLength(50, ErrorMessage = "Name length can't be more than 50.")]
public string Surname { get; set; }
[StringLength(50, ErrorMessage = "Name length can't be more than 50.")]
public string Nickname { get; set; }
[StringLength(50, ErrorMessage = "Name length can't be more than 50.")]
public string Image { get; set; }
public bool ExtraTime { get; set; }
[Range(0,100)]
public int Group { get; set; }
public List<String> Roles { get; set; }
}
}

@ -26,7 +26,7 @@ namespace adminBlazor.Pages
/// <summary>
/// The current item model
/// </summary>
private Models.User user = new Models.User()
private Models.UserModel user = new Models.UserModel()
{
Roles = new List<string>()
};
@ -34,13 +34,13 @@ namespace adminBlazor.Pages
private async void HandleValidSubmit()
{
// Get the current data
var currentData = await LocalStorage.GetItemAsync<List<User>>("data");
var currentData = await LocalStorage.GetItemAsync<List<UserModel>>("data");
// Simulate the Id
user.Id = currentData.Max(s => s.Id) + 1;
// Add the item to the current data
currentData.Add(new User
currentData.Add(new UserModel
{
Id = user.Id,
Name = user.Name,

@ -1,8 +1,9 @@
@page "/editUser/{Id:int}"
@using adminBlazor.Models
<h3>Edit</h3>
<h3>Edit</h3>
<h4>User id : @Id</h4>
<EditForm Model="@user" OnValidSubmit="@HandleValidSubmit">
<DataAnnotationsValidator />
<ValidationSummary />

@ -13,9 +13,8 @@ namespace adminBlazor.Pages
public int Id { get; set; }
//IDataService
[Inject]
public IDataService DataService { get; set; }
//public ILocalStorageService LocalStorage { get; set; }
[Inject]
public NavigationManager NavigationManager { get; set; }
@ -33,7 +32,7 @@ namespace adminBlazor.Pages
/// <summary>
/// The current item model
/// </summary>
private Models.User user = new Models.User()
private Models.UserModel user = new Models.UserModel()
{
Roles = new List<string>()
};
@ -49,16 +48,15 @@ namespace adminBlazor.Pages
protected override async Task OnInitializedAsync()
{
var item = await DataService.GetById(Id);
var fileContent = await File.ReadAllBytesAsync($"{WebHostEnvironment.WebRootPath}/images/default.png");
// var fileContent = await File.ReadAllBytesAsync($"{WebHostEnvironment.WebRootPath}/images/default.png");
if (File.Exists($"{WebHostEnvironment.WebRootPath}/images/{user.Name}.png"))
{
fileContent = await File.ReadAllBytesAsync($"{WebHostEnvironment.WebRootPath}/images/{item.Name}.png");
// fileContent = await File.ReadAllBytesAsync($"{WebHostEnvironment.WebRootPath}/images/{item.Name}.png");
}
// Set the model with the item
user = new User
user = new UserModel
{
Id = user.Id,
Name = user.Name,

@ -15,25 +15,25 @@
</NavLink>
</div>
<DataGrid TItem="User"
<DataGrid TItem="UserModel"
Data="@_users"
ReadData="@OnReadData"
TotalItems="@totalUser"
PageSize="10"
ShowPager
Responsive>
<DataGridColumn TItem="User" Field="@nameof(User.Id)" Caption="id" />
<DataGridColumn TItem="UserModel" Field="@nameof(UserModel.Id)" Caption="id" />
<!-- <DataGridColumn TItem="User" Field="@nameof(User.Password)" Caption="Password" /> -->
<DataGridColumn TItem="User" Field="@nameof(User.Name)" Caption="Name" />
<DataGridColumn TItem="User" Field="@nameof(User.Email)" Caption="Email" />
<DataGridColumn TItem="User" Field="@nameof(User.Surname)" Caption="Surname" />
<DataGridColumn TItem="User" Field="@nameof(User.Nickname)" Caption="Nickname" />
<DataGridColumn TItem="UserModel" Field="@nameof(UserModel.Name)" Caption="Name" />
<DataGridColumn TItem="UserModel" Field="@nameof(UserModel.Email)" Caption="Email" />
<DataGridColumn TItem="UserModel" Field="@nameof(UserModel.Surname)" Caption="Surname" />
<DataGridColumn TItem="UserModel" Field="@nameof(UserModel.Nickname)" Caption="Nickname" />
<!-- <DataGridColumn TItem="User" Field="@nameof(User.Image)" Caption="Image" /> -->
<DataGridColumn TItem="User" Field="@nameof(User.ExtraTime)" Caption="Extra Time" />
<DataGridColumn TItem="User" Field="@nameof(User.Group)" Caption="Group" />
<DataGridColumn TItem="User" Field="@nameof(User.Roles)" Caption="Roles">
<DataGridColumn TItem="UserModel" Field="@nameof(UserModel.ExtraTime)" Caption="Extra Time" />
<DataGridColumn TItem="UserModel" Field="@nameof(UserModel.Group)" Caption="Group" />
<DataGridColumn TItem="UserModel" Field="@nameof(UserModel.Roles)" Caption="Roles">
<DisplayTemplate>
@if (context is User user)
@if (context is UserModel user)
{
@if (user.Roles != null && user.Roles.Any())
{
@ -45,9 +45,8 @@
}
}
</DisplayTemplate>
</DataGridColumn>
<DataGridColumn TItem="User" Field="@nameof(User.Id)" Caption="Modifier">
<DataGridColumn TItem="UserModel" Field="@nameof(UserModel.Id)" Caption="Modifier">
<DisplayTemplate>
<a href="EditUser/@(context.Id)" class="btn btn-primary"><i class="fa fa-edit"></i> Editer</a>
</DisplayTemplate>

@ -11,7 +11,7 @@ namespace adminBlazor.Pages
{
public partial class List
{
private List<User> _users;
private List<UserModel> _users;
private int totalUser;
@ -33,18 +33,18 @@ namespace adminBlazor.Pages
return;
}
var currentData = await LocalStorage.GetItemAsync<User[]>("data");
var currentData = await LocalStorage.GetItemAsync<UserModel[]>("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<User[]>($"{NavigationManager.BaseUri}user.json").Result;
var originalData = Http.GetFromJsonAsync<UserModel[]>($"{NavigationManager.BaseUri}user.json").Result;
await LocalStorage.SetItemAsync("data", originalData);
}
}
private async Task OnReadData(DataGridReadDataEventArgs<User> e)
private async Task OnReadData(DataGridReadDataEventArgs<UserModel> e)
{
if (e.CancellationToken.IsCancellationRequested)
{
@ -53,12 +53,12 @@ namespace adminBlazor.Pages
// 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<User[]>("data")).Skip((e.Page - 1) * e.PageSize).Take(e.PageSize).ToList();
var response = (await LocalStorage.GetItemAsync<UserModel[]>("data")).Skip((e.Page - 1) * e.PageSize).Take(e.PageSize).ToList();
if (!e.CancellationToken.IsCancellationRequested)
{
totalUser = (await LocalStorage.GetItemAsync<List<User>>("data")).Count;
_users = new List<User>(response); // an actual data for the current page
totalUser = (await LocalStorage.GetItemAsync<List<UserModel>>("data")).Count;
_users = new List<UserModel>(response); // an actual data for the current page
}
}
}

@ -5,9 +5,10 @@ using Blazorise;
using Blazorise.Bootstrap;
using Blazorise.Icons.FontAwesome;
using Blazored.LocalStorage;
using adminBlazor.Services;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<IDataService, DataLocalService>();
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
@ -17,6 +18,7 @@ builder.Services.AddHttpClient();
builder.Services.AddBlazoredLocalStorage();
builder.Services
.AddBlazorise()
.AddBootstrapProviders()

@ -9,15 +9,28 @@ namespace adminBlazor.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 DataLocalService(ILocalStorageService localStorage)
{
_localStorage = localStorage; // Assure-toi que LocalStorage est initialisé correctement ici
}
public required ILocalStorageService LocalStorage { get; set; }
[Inject]
public required IWebHostEnvironment WebHostEnvironment { get; set; }
public DataLocalService dataLocalService => throw new NotImplementedException();
public Task Add(User model)
public Task Add(UserModel model)
{
throw new NotImplementedException();
}
@ -27,10 +40,11 @@ namespace adminBlazor.Services
throw new NotImplementedException();
}
public async Task<User> GetById(int id)
public async Task<UserModel> GetById(int id)
{
// Get the current data
var currentData = await LocalStorage.GetItemAsync<List<User>>("data");
//var currentData = await LocalStorage.GetItemAsync<User[]>("user.json");
var currentData = await _localStorage.GetItemAsync<List<UserModel>>("data");
var user = currentData.FirstOrDefault(w => w.Id == id);
@ -42,15 +56,15 @@ namespace adminBlazor.Services
return user;
}
public Task<List<User>> List(int currentPage, int pageSize)
public Task<List<UserModel>> List(int currentPage, int pageSize)
{
throw new NotImplementedException();
}
public async Task Update(int id, User model)
public async Task Update(int id, UserModel model)
{
// Get the current data
var currentData = await LocalStorage.GetItemAsync<List<User>>("data");
var currentData = await _localStorage.GetItemAsync<List<UserModel>>("data");
var user = currentData.FirstOrDefault(w => w.Id == id);
@ -60,30 +74,30 @@ namespace adminBlazor.Services
}
// Save the image
var imagePathInfo = new DirectoryInfo($"{WebHostEnvironment.WebRootPath}/images");
// var imagePathInfo = new DirectoryInfo($"{WebHostEnvironment.WebRootPath}/images");
// Check if the folder "images" exist
if (!imagePathInfo.Exists)
// if (!imagePathInfo.Exists)
{
imagePathInfo.Create();
// imagePathInfo.Create();
}
// Delete the previous image
if (user.Name != model.Name)
{
var oldFileName = new FileInfo($"{imagePathInfo}/{user.Name}.png");
// var oldFileName = new FileInfo($"{imagePathInfo}/{user.Name}.png");
if (oldFileName.Exists)
// if (oldFileName.Exists)
{
File.Delete(oldFileName.FullName);
// File.Delete(oldFileName.FullName);
}
}
// Determine the image name
var fileName = new FileInfo($"{imagePathInfo}/{model.Name}.png");
//var fileName = new FileInfo($"{imagePathInfo}/{model.Name}.png");
// Write the file content
//await File.WriteAllBytesAsync(fileName.FullName, model.Image);
// await File.WriteAllBytesAsync(fileName.FullName, model.Image);
UserFactory.Update(user, model);
// Modify the content of the item
@ -98,7 +112,7 @@ namespace adminBlazor.Services
user.Image = model.Image;
// Save the data
await LocalStorage.SetItemAsync("data", currentData);
await _localStorage.SetItemAsync("data", currentData);
}
}
}

@ -7,15 +7,15 @@ namespace adminBlazor.Services
public interface IDataService
{
Task Add(User model);
Task Add(UserModel model);
Task<int> Count();
Task<List<User>> List(int currentPage, int pageSize);
Task<List<UserModel>> List(int currentPage, int pageSize);
Task<User> GetById(int id);
Task<UserModel> GetById(int id);
Task Update(int id, User model);
Task Update(int id, UserModel model);
}
}

@ -8,4 +8,5 @@
@using Microsoft.JSInterop
@using adminBlazor
@using adminBlazor.Shared
@using Blazorise.DataGrid;
@using Blazorise.DataGrid
@using adminBlazor.Services

Loading…
Cancel
Save