// Controllers/TeamController.cs - 简化版本(无时间戳)
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using UserManagementSystem.Web.Data;
using UserManagementSystem.Web.Models;
using UserManagementSystem.Web.Models.ViewModels;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace UserManagementSystem.Web.Controllers
{
[Authorize]
[Route("Team")]
public class TeamController : Controller
{
private readonly ApplicationDbContext _context;
public TeamController(ApplicationDbContext context)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
}
#region 列表显示
[HttpGet("")]
[HttpGet("Index")]
public async Task<IActionResult> Index(TeamListRequestModel request)
{
const int pageSize = 10;
try
{
var teamsQuery = BuildTeamsQuery(request);
var totalItems = await teamsQuery.CountAsync();
var totalPages = (int)Math.Ceiling(totalItems / (double)pageSize);
var currentPage = ValidatePageNumber(request.Page, totalPages);
var skipCount = (currentPage - 1) * pageSize;
var teams = await teamsQuery
.OrderBy(t => t.Group.Cmb.SortOrder)
.ThenBy(t => t.Group.Cmb.Name)
.ThenBy(t => t.Group.SortOrder)
.ThenBy(t => t.Group.Name)
.ThenBy(t => t.SortOrder)
.ThenBy(t => t.Name)
.Skip(skipCount)
.Take(pageSize)
.ToListAsync();
var viewModel = CreateTeamListViewModel(teams, currentPage, totalPages, totalItems, request);
await SetDropdownDataAsync();
return View(viewModel);
}
catch (Exception ex)
{
LogError("Index", ex);
TempData["ErrorMessage"] = "加载数据失败,请稍后重试";
var emptyModel = new TeamListViewModel();
await SetDropdownDataAsync();
return View(emptyModel);
}
}
private IQueryable<Team> BuildTeamsQuery(TeamListRequestModel request)
{
var query = _context.Teams
.Include(t => t.Group)
.ThenInclude(g => g.Cmb)
.AsQueryable();
if (request.SelectedCmbId > 0)
{
query = query.Where(t => t.Group.CmbId == request.SelectedCmbId);
}
if (request.SelectedGroupId > 0)
{
query = query.Where(t => t.GroupId == request.SelectedGroupId);
}
if (!string.IsNullOrWhiteSpace(request.SearchTerm))
{
var searchTerm = request.SearchTerm.Trim();
query = query.Where(t =>
t.Name.Contains(searchTerm) ||
t.Group.Name.Contains(searchTerm) ||
t.Group.Cmb.Name.Contains(searchTerm));
}
return query;
}
private int ValidatePageNumber(int page, int totalPages)
{
return Math.Max(1, Math.Min(page, totalPages > 0 ? totalPages : 1));
}
private TeamListViewModel CreateTeamListViewModel(
List<Team> teams,
int currentPage,
int totalPages,
int totalItems,
TeamListRequestModel request)
{
return new TeamListViewModel
{
Teams = teams.Select(t => new TeamListItemViewModel
{
Id = t.Id,
Name = t.Name,
GroupName = t.Group?.Name ?? string.Empty,
CmbName = t.Group?.Cmb?.Name ?? string.Empty,
SortOrder = t.SortOrder,
GroupId = t.GroupId
}).ToList(),
CurrentPage = currentPage,
TotalPages = totalPages,
TotalItems = totalItems,
SearchTerm = request.SearchTerm ?? string.Empty,
SelectedGroupId = request.SelectedGroupId,
SelectedCmbId = request.SelectedCmbId
};
}
#endregion
#region 创建操作
[HttpGet("Create")]
public async Task<IActionResult> Create()
{
try
{
var viewModel = new TeamEditViewModel();
await SetDropdownDataAsync();
if (!(ViewBag.AllGroups as List<GroupSelectViewModel>)?.Any() ?? true)
{
TempData["WarningMessage"] = "没有可用的组别,请先创建组别";
}
return View(viewModel);
}
catch (Exception ex)
{
LogError("Create GET", ex);
TempData["ErrorMessage"] = "加载创建页面失败";
ViewBag.AllGroups = new List<GroupSelectViewModel>();
return View(new TeamEditViewModel());
}
}
[HttpPost("Create")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(TeamEditViewModel model)
{
if (!ModelState.IsValid)
{
await SetDropdownDataAsync();
return View(model);
}
try
{
if (await IsTeamNameExists(model.Name, model.GroupId, 0))
{
ModelState.AddModelError("Name", "该组别下已存在同名队别");
await SetDropdownDataAsync();
return View(model);
}
var team = new Team
{
Name = model.Name,
GroupId = model.GroupId,
SortOrder = model.SortOrder
};
_context.Teams.Add(team);
await _context.SaveChangesAsync();
TempData["SuccessMessage"] = "队别创建成功!";
return RedirectToAction(nameof(Index));
}
catch (DbUpdateException ex)
{
LogError("Create POST", ex);
TempData["ErrorMessage"] = $"数据库更新失败: {ex.InnerException?.Message ?? ex.Message}";
}
catch (Exception ex)
{
LogError("Create POST", ex);
TempData["ErrorMessage"] = $"创建失败: {ex.Message}";
}
await SetDropdownDataAsync();
return View(model);
}
#endregion
#region 编辑操作
[HttpGet("Edit/{id}")]
public async Task<IActionResult> Edit(int id)
{
try
{
var team = await _context.Teams.FindAsync(id);
if (team == null)
{
TempData["ErrorMessage"] = "未找到指定的队别";
return RedirectToAction(nameof(Index));
}
var viewModel = new TeamEditViewModel
{
Id = team.Id,
Name = team.Name,
GroupId = team.GroupId,
SortOrder = team.SortOrder
};
await SetDropdownDataAsync();
return View(viewModel);
}
catch (Exception ex)
{
LogError($"Edit GET (id: {id})", ex);
TempData["ErrorMessage"] = "加载编辑页面失败";
ViewBag.AllGroups = new List<GroupSelectViewModel>();
return RedirectToAction(nameof(Index));
}
}
[HttpPost("Edit/{id}")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, TeamEditViewModel model)
{
if (id != model.Id)
{
return NotFound();
}
if (!ModelState.IsValid)
{
await SetDropdownDataAsync();
return View(model);
}
try
{
if (await IsTeamNameExists(model.Name, model.GroupId, id))
{
ModelState.AddModelError("Name", "该组别下已存在同名队别");
await SetDropdownDataAsync();
return View(model);
}
var team = await _context.Teams.FindAsync(id);
if (team == null)
{
TempData["ErrorMessage"] = "未找到要编辑的队别";
return RedirectToAction(nameof(Index));
}
team.Name = model.Name;
team.GroupId = model.GroupId;
team.SortOrder = model.SortOrder;
_context.Update(team);
await _context.SaveChangesAsync();
TempData["SuccessMessage"] = "队别更新成功!";
return RedirectToAction(nameof(Index));
}
catch (DbUpdateConcurrencyException)
{
if (!await TeamExists(model.Id))
{
TempData["ErrorMessage"] = "记录已被删除或不存在";
return RedirectToAction(nameof(Index));
}
else
{
ModelState.AddModelError("", "保存时发生并发冲突,请刷新页面后重试");
}
}
catch (DbUpdateException ex)
{
LogError($"Edit POST (id: {id})", ex);
TempData["ErrorMessage"] = $"数据库更新失败: {ex.InnerException?.Message ?? ex.Message}";
}
catch (Exception ex)
{
LogError($"Edit POST (id: {id})", ex);
TempData["ErrorMessage"] = $"更新失败: {ex.Message}";
}
await SetDropdownDataAsync();
return View(model);
}
#endregion
#region 删除操作
[HttpGet("Delete/{id}")]
public async Task<IActionResult> Delete(int id)
{
try
{
var team = await _context.Teams
.Include(t => t.Group)
.ThenInclude(g => g.Cmb)
.FirstOrDefaultAsync(t => t.Id == id);
if (team == null)
{
TempData["ErrorMessage"] = "未找到要删除的队别";
return RedirectToAction(nameof(Index));
}
var viewModel = new TeamDeleteViewModel
{
Id = team.Id,
Name = team.Name,
GroupName = team.Group?.Name ?? string.Empty,
CmbName = team.Group?.Cmb?.Name ?? string.Empty,
SortOrder = team.SortOrder
};
await SetDropdownDataAsync();
return View(viewModel);
}
catch (Exception ex)
{
LogError($"Delete GET (id: {id})", ex);
TempData["ErrorMessage"] = "加载删除页面失败";
return RedirectToAction(nameof(Index));
}
}
[HttpPost("Delete/{id}")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
try
{
var team = await _context.Teams.FindAsync(id);
if (team == null)
{
TempData["ErrorMessage"] = "记录已被删除或不存在";
return RedirectToAction(nameof(Index));
}
_context.Teams.Remove(team);
await _context.SaveChangesAsync();
TempData["SuccessMessage"] = "队别删除成功!";
return RedirectToAction(nameof(Index));
}
catch (DbUpdateException ex)
{
LogError($"Delete POST (id: {id})", ex);
TempData["ErrorMessage"] = $"删除失败,可能与其他数据有关联: {ex.InnerException?.Message ?? ex.Message}";
}
catch (Exception ex)
{
LogError($"Delete POST (id: {id})", ex);
TempData["ErrorMessage"] = $"删除失败: {ex.Message}";
}
return RedirectToAction(nameof(Delete), new { id = id });
}
#endregion
#region 辅助方法
private async Task<bool> IsTeamNameExists(string name, int groupId, int excludeId)
{
if (string.IsNullOrWhiteSpace(name)) return false;
return await _context.Teams
.AnyAsync(t => t.Id != excludeId &&
t.Name == name.Trim() &&
t.GroupId == groupId);
}
private async Task<bool> TeamExists(int id)
{
return await _context.Teams.AnyAsync(e => e.Id == id);
}
private async Task SetDropdownDataAsync()
{
try
{
var cmbs = await _context.Cmbs
.OrderBy(c => c.SortOrder)
.ThenBy(c => c.Name)
.ToListAsync();
ViewBag.AllCmbs = cmbs ?? new List<Cmb>();
var groups = await GetGroupSelectViewModelsAsync();
ViewBag.AllGroups = groups ?? new List<GroupSelectViewModel>();
}
catch (Exception ex)
{
LogError("SetDropdownDataAsync", ex);
ViewBag.AllCmbs = new List<Cmb>();
ViewBag.AllGroups = new List<GroupSelectViewModel>();
}
}
private async Task<List<GroupSelectViewModel>> GetGroupSelectViewModelsAsync()
{
try
{
var groups = await _context.Groups
.Include(g => g.Cmb)
.Where(g => g.Cmb != null && !string.IsNullOrEmpty(g.Name))
.OrderBy(g => g.Cmb.SortOrder)
.ThenBy(g => g.Cmb.Name)
.ThenBy(g => g.SortOrder)
.ThenBy(g => g.Name)
.Select(g => new GroupSelectViewModel
{
Id = g.Id,
Name = g.Name ?? string.Empty,
CmbName = g.Cmb.Name ?? string.Empty
})
.ToListAsync();
return groups ?? new List<GroupSelectViewModel>();
}
catch (Exception ex)
{
LogError("GetGroupSelectViewModelsAsync", ex);
return new List<GroupSelectViewModel>();
}
}
private void LogError(string actionName, Exception ex)
{
Console.WriteLine($"Error in {nameof(TeamController)}.{actionName}: {ex.Message}");
Console.WriteLine($"Inner exception: {ex.InnerException?.Message}");
}
#endregion
}
}
在这个代码修改
最新发布