littleshop/Areas/Admin/Controllers/CategoriesController.cs
2025-08-20 13:20:19 +01:00

92 lines
2.4 KiB
C#

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using LittleShop.Services;
using LittleShop.DTOs;
namespace LittleShop.Areas.Admin.Controllers;
[Area("Admin")]
[Authorize(Policy = "AdminOnly")]
public class CategoriesController : Controller
{
private readonly ICategoryService _categoryService;
public CategoriesController(ICategoryService categoryService)
{
_categoryService = categoryService;
}
public async Task<IActionResult> Index()
{
var categories = await _categoryService.GetAllCategoriesAsync();
return View(categories);
}
public IActionResult Create()
{
return View(new CreateCategoryDto());
}
[HttpPost]
public async Task<IActionResult> Create(CreateCategoryDto model)
{
Console.WriteLine($"Received Category: Name='{model?.Name}', Description='{model?.Description}'");
Console.WriteLine($"ModelState.IsValid: {ModelState.IsValid}");
if (!ModelState.IsValid)
{
foreach (var error in ModelState)
{
Console.WriteLine($"ModelState Error - Key: {error.Key}, Errors: {string.Join(", ", error.Value.Errors.Select(e => e.ErrorMessage))}");
}
return View(model);
}
await _categoryService.CreateCategoryAsync(model);
return RedirectToAction(nameof(Index));
}
public async Task<IActionResult> Edit(Guid id)
{
var category = await _categoryService.GetCategoryByIdAsync(id);
if (category == null)
{
return NotFound();
}
var model = new UpdateCategoryDto
{
Name = category.Name,
Description = category.Description,
IsActive = category.IsActive
};
ViewData["CategoryId"] = id;
return View(model);
}
[HttpPost]
public async Task<IActionResult> Edit(Guid id, UpdateCategoryDto model)
{
if (!ModelState.IsValid)
{
ViewData["CategoryId"] = id;
return View(model);
}
var success = await _categoryService.UpdateCategoryAsync(id, model);
if (!success)
{
return NotFound();
}
return RedirectToAction(nameof(Index));
}
[HttpPost]
public async Task<IActionResult> Delete(Guid id)
{
await _categoryService.DeleteCategoryAsync(id);
return RedirectToAction(nameof(Index));
}
}