Skip to content

Commit 54cb72b

Browse files
hoanghoang
hoang
authored and
hoang
committed
alo
1 parent adc364f commit 54cb72b

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

51 files changed

+12239
-507
lines changed

.editorconfig

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
[*.cs]
2+
3+
# IDE0055: Fix formatting
4+
dotnet_diagnostic.IDE0055.severity = none

Lab03.sln

+6-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,12 @@ Microsoft Visual Studio Solution File, Format Version 12.00
33
# Visual Studio Version 17
44
VisualStudioVersion = 17.9.34714.143
55
MinimumVisualStudioVersion = 10.0.40219.1
6-
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lab03", "Lab03\Lab03.csproj", "{89AE1A7D-5303-4FCE-A990-260EDE5AC88F}"
6+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Lab03", "Lab03\Lab03.csproj", "{89AE1A7D-5303-4FCE-A990-260EDE5AC88F}"
7+
EndProject
8+
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{BC245B23-57CB-4E22-B8D1-7724AED963CA}"
9+
ProjectSection(SolutionItems) = preProject
10+
.editorconfig = .editorconfig
11+
EndProjectSection
712
EndProject
813
Global
914
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
using Lab03.Areas.Admin.Controllers.Lab03.Models;
2+
using Lab03.Models;
3+
using Lab03.Repositories;
4+
using Microsoft.AspNetCore.Authorization;
5+
using Microsoft.AspNetCore.Mvc;
6+
using Microsoft.AspNetCore.Mvc.Rendering;
7+
8+
namespace Lab03.Areas.Admin.Controllers
9+
{
10+
[Area("Admin")]
11+
[Authorize(Roles =SD.Role_Admin)]
12+
public class ProductManagerController : Controller
13+
{
14+
private readonly IProductRepository _productRepository;
15+
private readonly ICategoryRepository _categoryRepository;
16+
public ProductManagerController(IProductRepository productRepository, ICategoryRepository categoryRepository)
17+
{
18+
_productRepository = productRepository;
19+
_categoryRepository = categoryRepository;
20+
}
21+
// Hiển thị danh sách sản phẩm
22+
public async Task<IActionResult> Index()
23+
{
24+
var products = await _productRepository.GetAllAsync();
25+
return View(products);
26+
}
27+
// Hiển thị form thêm sản phẩm mới
28+
public async Task<IActionResult> Create()
29+
{
30+
var categories = await _categoryRepository.GetAllAsync();
31+
ViewBag.Categories = new SelectList(categories, "Id", "Name");
32+
return View();
33+
}
34+
// Xử lý thêm sản phẩm mới
35+
[HttpPost]
36+
public async Task<IActionResult> Create(Product product, IFormFile ImageUrl)
37+
{
38+
if (ModelState.IsValid)
39+
{
40+
if (ImageUrl != null)
41+
{
42+
// Lưu hình ảnh đại diện
43+
product.ImageUrl = await SaveImage(ImageUrl);
44+
}
45+
46+
await _productRepository.AddAsync(product);
47+
return RedirectToAction(nameof(Index));
48+
}
49+
// Nếu ModelState không hợp lệ, hiển thị form với dữ liệu đã nhập
50+
var categories = await _categoryRepository.GetAllAsync();
51+
ViewBag.Categories = new SelectList(categories, "Id", "Name");
52+
return View(product);
53+
}
54+
// Show the product update form
55+
public async Task<IActionResult> Edit(int id)
56+
{
57+
var product = await _productRepository.GetByIdAsync(id);
58+
if (product == null)
59+
{
60+
return NotFound();
61+
}
62+
var categories = await _categoryRepository.GetAllAsync();
63+
ViewBag.Categories = new SelectList(categories, "Id", "Name");
64+
return View(product);
65+
}
66+
// Process the product update
67+
[HttpPost]
68+
public async Task<IActionResult> Edit(Product product, IFormFile ImageUrl)
69+
{
70+
if (ModelState.IsValid)
71+
{
72+
if (ImageUrl != null)
73+
{
74+
// Lưu hình ảnh đại diện
75+
product.ImageUrl = await SaveImage(ImageUrl);
76+
}
77+
await _productRepository.UpdateAsync(product);
78+
return RedirectToAction("Index");
79+
}
80+
return View(product);
81+
}
82+
83+
public async Task<IActionResult> Details(int id)
84+
{
85+
var product = await _productRepository.GetByIdAsync(id);
86+
if (product == null)
87+
{
88+
return NotFound();
89+
}
90+
return View(product);
91+
}
92+
// Hiển thị form xác nhận xóa sản phẩm
93+
public async Task<IActionResult> Delete(int id)
94+
{
95+
var product = await _productRepository.GetByIdAsync(id);
96+
if (product == null)
97+
{
98+
return NotFound();
99+
}
100+
return View(product);
101+
}
102+
// Xử lý xóa sản phẩm
103+
[HttpPost, ActionName("Delete")]
104+
public async Task<IActionResult> DeleteConfirmed(int id)
105+
{
106+
await _productRepository.DeleteAsync(id);
107+
return RedirectToAction(nameof(Index));
108+
}
109+
110+
private async Task<string> SaveImage(IFormFile image)
111+
{
112+
var savePath = Path.Combine("wwwroot/images", image.FileName);
113+
// Thay đổi đường dẫn theo cấu hình của bạn
114+
using (var fileStream = new FileStream(savePath, FileMode.Create))
115+
{
116+
await image.CopyToAsync(fileStream);
117+
}
118+
return "/images/" + image.FileName;
119+
// Trả về đường dẫn tương đối
120+
}
121+
}
122+
}

Lab03/Areas/Identity/Pages/Account/Register.cshtml Lab03/Areas/Admin/Identity/Pages/Account/Register.cshtml

+3
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,9 @@
3232
<label asp-for="Input.ConfirmPassword">Confirm Password</label>
3333
<span asp-validation-for="Input.ConfirmPassword" class="text-danger"></span>
3434
</div>
35+
<div class="form-floating mb-3">
36+
<select asp-for="Input.Role" asp-items="@Model.Input.RoleList" class="from-control"><option disabled selected>Select Role</option></select>
37+
</div>
3538
<button id="registerSubmit" type="submit" class="w-100 btn btn-lg btn-primary">Register</button>
3639
</form>
3740
</div>

Lab03/Areas/Identity/Pages/Account/Register.cshtml.cs Lab03/Areas/Admin/Identity/Pages/Account/Register.cshtml.cs

+34-2
Original file line numberDiff line numberDiff line change
@@ -19,25 +19,31 @@
1919
using Microsoft.AspNetCore.Mvc.RazorPages;
2020
using Microsoft.AspNetCore.WebUtilities;
2121
using Microsoft.Extensions.Logging;
22+
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
23+
using Microsoft.AspNetCore.Mvc.Rendering;
24+
using Lab03.Areas.Admin.Controllers.Lab03.Models;
2225

2326
namespace Lab03.Areas.Identity.Pages.Account
2427
{
2528
public class RegisterModel : PageModel
2629
{
2730
private readonly SignInManager<ApplicationUser> _signInManager;
31+
private readonly RoleManager<IdentityRole>_roleManager;
2832
private readonly UserManager<ApplicationUser> _userManager;
2933
private readonly IUserStore<ApplicationUser> _userStore;
3034
private readonly IUserEmailStore<ApplicationUser> _emailStore;
3135
private readonly ILogger<RegisterModel> _logger;
3236
private readonly IEmailSender _emailSender;
3337

3438
public RegisterModel(
39+
RoleManager<IdentityRole> roleManager,
3540
UserManager<ApplicationUser> userManager,
3641
IUserStore<ApplicationUser> userStore,
3742
SignInManager<ApplicationUser> signInManager,
3843
ILogger<RegisterModel> logger,
3944
IEmailSender emailSender)
4045
{
46+
_roleManager = roleManager;
4147
_userManager = userManager;
4248
_userStore = userStore;
4349
_emailStore = GetEmailStore();
@@ -52,7 +58,7 @@ public RegisterModel(
5258
/// </summary>
5359
[BindProperty]
5460
public InputModel Input { get; set; }
55-
61+
5662
/// <summary>
5763
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
5864
/// directly from your code. This API may change or be removed in future releases.
@@ -73,6 +79,7 @@ public class InputModel
7379
{
7480
[Required]
7581
public string FullName { get; set; }
82+
7683
/// <summary>
7784
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
7885
/// directly from your code. This API may change or be removed in future releases.
@@ -100,11 +107,29 @@ public class InputModel
100107
[Display(Name = "Confirm password")]
101108
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
102109
public string ConfirmPassword { get; set; }
110+
public string ?Role { get; set; }
111+
[ValidateNever]
112+
public IEnumerable<SelectListItem> RoleList { get; set; }
103113
}
104114

105115

106116
public async Task OnGetAsync(string returnUrl = null)
107117
{
118+
if (!_roleManager.RoleExistsAsync(SD.Role_Customer).GetAwaiter().GetResult())
119+
{
120+
_roleManager.CreateAsync(new IdentityRole(SD.Role_Customer)).GetAwaiter().GetResult();
121+
_roleManager.CreateAsync(new IdentityRole(SD.Role_Employee)).GetAwaiter().GetResult();
122+
_roleManager.CreateAsync(new IdentityRole(SD.Role_Admin)).GetAwaiter().GetResult();
123+
_roleManager.CreateAsync(new IdentityRole(SD.Role_Company)).GetAwaiter().GetResult();
124+
}
125+
Input = new()
126+
{
127+
RoleList = _roleManager.Roles.Select(x => x.Name).Select(i => new SelectListItem
128+
{
129+
Text = i,
130+
Value = i
131+
})
132+
};
108133
ReturnUrl = returnUrl;
109134
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
110135
}
@@ -124,7 +149,14 @@ public async Task<IActionResult> OnPostAsync(string returnUrl = null)
124149
if (result.Succeeded)
125150
{
126151
_logger.LogInformation("User created a new account with password.");
127-
152+
if (!String.IsNullOrEmpty(Input.Role))
153+
{
154+
await _userManager.AddToRoleAsync(user, Input.Role);
155+
}
156+
else
157+
{
158+
await _userManager.AddToRoleAsync(user,SD.Role_Customer);
159+
}
128160
var userId = await _userManager.GetUserIdAsync(user);
129161
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
130162
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
@model Lab03.Models.Product
2+
3+
@{
4+
ViewData["Title"] = "Create";
5+
}
6+
7+
<a asp-area="Admin" asp-controller="ProductManager" asp-action="Create">Them San Pham</a>
8+
<h4>Product</h4>
9+
<hr />
10+
<div class="row">
11+
<div class="col-md-4">
12+
<form asp-action="Create" enctype="multipart/form-data">
13+
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
14+
<div class="form-group">
15+
<label asp-for="Name" class="control-label"></label>
16+
<input asp-for="Name" class="form-control" />
17+
<span asp-validation-for="Name" class="text-danger"></span>
18+
</div>
19+
<div class="form-group">
20+
<label asp-for="Price" class="control-label"></label>
21+
<input asp-for="Price" class="form-control" />
22+
<span asp-validation-for="Price" class="text-danger"></span>
23+
</div>
24+
<div class="form-group">
25+
<label asp-for="Description" class="control-label"></label>
26+
<input asp-for="Description" class="form-control" />
27+
<span asp-validation-for="Description" class="text-danger"></span>
28+
</div>
29+
<div class="form-group">
30+
<label asp-for="ImageUrl" class="control-label"></label>
31+
<input type="file" asp-for="ImageUrl" class="form-control" />
32+
<span asp-validation-for="ImageUrl" class="text-danger"></span>
33+
</div>
34+
<div class="form-group">
35+
<label asp-for="CategoryId" class="control-label"></label>
36+
<select asp-for="CategoryId" asp-items="ViewBag.Categories"
37+
class="form-control"></select>
38+
</div>
39+
<div class="form-group">
40+
<input type="submit" value="Create" class="btn btn-primary" />
41+
</div>
42+
</form>
43+
</div>
44+
</div>
45+
46+
<div>
47+
<a asp-action="Index">Back to List</a>
48+
</div>
49+
50+
@section Scripts {
51+
@{
52+
await Html.RenderPartialAsync("_ValidationScriptsPartial");
53+
}
54+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
@model Lab03.Models.Product
2+
3+
@{
4+
ViewData["Title"] = "Delete";
5+
}
6+
7+
<h1>Delete</h1>
8+
9+
<h3>Are you sure you want to delete this?</h3>
10+
<div>
11+
<h4>Product</h4>
12+
<hr />
13+
<dl class="row">
14+
<dt class="col-sm-2">
15+
@Html.DisplayNameFor(model => model.Name)
16+
</dt>
17+
<dd class="col-sm-10">
18+
@Html.DisplayFor(model => model.Name)
19+
</dd>
20+
<dt class="col-sm-2">
21+
@Html.DisplayNameFor(model => model.Price)
22+
</dt>
23+
<dd class="col-sm-10">
24+
@Html.DisplayFor(model => model.Price)
25+
</dd>
26+
<dt class="col-sm-2">
27+
@Html.DisplayNameFor(model => model.Description)
28+
</dt>
29+
<dd class="col-sm-10">
30+
@Html.DisplayFor(model => model.Description)
31+
</dd>
32+
<dt class="col-sm-2">
33+
@Html.DisplayNameFor(model => model.ImageUrl)
34+
</dt>
35+
<dd class="col-sm-10">
36+
<img src="@Model.ImageUrl" width="150px" />
37+
</dd>
38+
<dt class="col-sm-2">
39+
@Html.DisplayNameFor(model => model.Category)
40+
</dt>
41+
<dd class="col-sm-10">
42+
@Html.DisplayFor(model => model.Category.Name)
43+
</dd>
44+
</dl>
45+
46+
<form asp-action="Delete" enctype="multipart/form-data">
47+
<input type="hidden" asp-for="Id" />
48+
<input type="submit" value="Delete" class="btn btn-danger" /> |
49+
<a asp-action="Index">Back to List</a>
50+
</form>
51+
</div>

0 commit comments

Comments
 (0)