RedirectToAction

本文详细解析了MVC中重定向的各种方式,包括使用RedirectResult和RedirectPermanent进行HTTP302和HTTP301重定向的方法,以及如何利用RedirectToRoute系列辅助方法根据路由表生成网址,适用于网站改版时的页面重定向。
RedirectResult:运行重新导向到其他网址,在RedirectResult的内部,基本上还是以Response.Redirect方法响应HTTP 302暂时导向。
eg:
public ActionResult Redirect()
{
return Redirect("/Home/NewIndex");
}

在mvc3版本之后,System.Web.Mvc.Controller类型还内建了一个RedirectPermanent辅助方法,可以让Action响应HTTP 301永久导向,使用HTTP 301永久导向还可以提升SEO效果,可保留原本页面网址的网页排名Ranking记录,并自动迁移到转向的下一页,这对于网站改版导致网站部分页面的网址发生变更时非常使用。
eg:
public ActionResult Redirect()
{
return RedirectPermanent("/Home/NewIndex");
}

RedirectToRoute:与前者类似,不够它会替你运算所有现有的网址路由值RouteValue,并比对网址路由表RouteTable中的每条规则,有助于生成mvc的网址。

控制器类别中有四个与RedirectToRoute有关的辅助方法
1,RedirectToAction
2,RedirectToActionPermanent
3,RedirectToRoute
4,RedirectToRoutePermanent
上述1,2是一个比较简单的版本,直接传入Action名称就可设置让浏览器转向该Action的网址,也可以传入新增的RouteValue值。
eg:
public ActionResult RedirectToActionSample()
{
//转址到同控制器的另一个Action
return RedirectToAction("SamplePage");
//转址到指定控制器的特定action并采用http 301永久转址
return RedirectToActionPermanent("List","Member");
//转址到MemberController的ListAction,并且加上page这个RouteValue
return RedirectToAction("List","Member",new { page=3});
}
3,4则是较高级的版本,可利用在Global.asax中定义的网址路由表来指定不同的转向网址,
eg:
public ActionResult aaa()
{
//转址到同控制器的另一个Action
return RedirectToRoute( new { action="SamplePage"});
//转址到指定控制器的特定action
return RedirectToRoute( new { controller="Member",action="List"});
//转址到MemberController的List Action,并且加上page这个RouteValue
return RedirectToRoute( new { controller="Member", action="List",page=3})
//转址到App_Start\RouteConfig.cs中的registerRoutes方法定义的网址路由表中的某个路由
return RedirectToRoute(RouteConfig.cs中某个MapRoute下配置的路由name);
}

---------------------

本文来自 glacier12 的优快云 博客 ,全文地址请点击:https://blog.youkuaiyun.com/glacier12/article/details/49999253?utm_source=copy 

 

转载于:https://www.cnblogs.com/lbx6935/p/9688371.html

// 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; namespace UserManagementSystem.Web.Controllers { [Authorize] public class TeamController : Controller { private readonly ApplicationDbContext _context; public TeamController(ApplicationDbContext context) { _context = context; } // GET: /Team - 列表页面 public async Task<IActionResult> Index(string search = "", int groupId = 0, int cmbId = 0, int page = 1) { const int pageSize = 10; try { var teamsQuery = _context.Teams .Include(t => t.Group) .ThenInclude(g => g.Cmb) .AsQueryable(); // 按组别筛选 if (groupId > 0) { teamsQuery = teamsQuery.Where(t => t.GroupId == groupId); } // 按行政村筛选 if (cmbId > 0) { teamsQuery = teamsQuery.Where(t => t.Group.CmbId == cmbId); } // 搜索 if (!string.IsNullOrWhiteSpace(search)) { search = search.Trim(); teamsQuery = teamsQuery.Where(t => t.Name.Contains(search) || t.Group.Name.Contains(search) || t.Group.Cmb.Name.Contains(search)); } var totalItems = await teamsQuery.CountAsync(); var totalPages = (int)Math.Ceiling(totalItems / (double)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((page - 1) * pageSize) .Take(pageSize) .ToListAsync(); var viewModel = new TeamListViewModel { Teams = teams.Select(t => new TeamListItemViewModel { Id = t.Id, Name = t.Name, GroupName = t.Group.Name, CmbName = t.Group.Cmb.Name, SortOrder = t.SortOrder, GroupId = t.GroupId }).ToList(), CurrentPage = page, TotalPages = totalPages, SearchTerm = search, SelectedGroupId = groupId, SelectedCmbId = cmbId }; // 获取筛选选项 ViewBag.AllGroups = await _context.Groups .Include(g => g.Cmb) .OrderBy(g => g.Cmb.SortOrder) .ThenBy(g => g.Cmb.Name) .ThenBy(g => g.SortOrder) .ThenBy(g => g.Name) .Select(g => new { g.Id, g.Name, CmbName = g.Cmb.Name }) .ToListAsync(); ViewBag.AllCmbs = await _context.Cmbs .OrderBy(c => c.SortOrder) .ThenBy(c => c.Name) .ToListAsync(); return View(viewModel); } catch (Exception ex) { TempData["ErrorMessage"] = $"加载数据失败: {ex.Message}"; return View(new TeamListViewModel()); } } // GET: /Team/Create - 创建页面 public async Task<IActionResult> Create() { var viewModel = new TeamEditViewModel(); // 获取所有组别用于下拉选择 ViewBag.AllGroups = await _context.Groups .Include(g => g.Cmb) .OrderBy(g => g.Cmb.SortOrder) .ThenBy(g => g.Cmb.Name) .ThenBy(g => g.SortOrder) .ThenBy(g => g.Name) .Select(g => new { g.Id, g.Name, CmbName = g.Cmb.Name }) .ToListAsync(); return View(viewModel); } // POST: /Team/Create [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create(TeamEditViewModel model) { if (ModelState.IsValid) { try { // 检查队名是否重复(同一组别下) var exists = await _context.Teams .AnyAsync(t => t.Name == model.Name && t.GroupId == model.GroupId); if (exists) { ModelState.AddModelError("Name", "该组别下已存在同名队别"); ViewBag.AllGroups = await _context.Groups.ToListAsync(); 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 (Exception ex) { TempData["ErrorMessage"] = $"创建失败: {ex.Message}"; ViewBag.AllGroups = await _context.Groups.ToListAsync(); return View(model); } } ViewBag.AllGroups = await _context.Groups.ToListAsync(); return View(model); } // GET: /Team/Edit/5 - 编辑页面 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 }; ViewBag.AllGroups = await _context.Groups .Include(g => g.Cmb) .OrderBy(g => g.Cmb.SortOrder) .ThenBy(g => g.Cmb.Name) .ThenBy(g => g.SortOrder) .ThenBy(g => g.Name) .Select(g => new { g.Id, g.Name, CmbName = g.Cmb.Name }) .ToListAsync(); return View(viewModel); } catch (Exception ex) { TempData["ErrorMessage"] = $"加载编辑页面失败: {ex.Message}"; return RedirectToAction(nameof(Index)); } } // POST: /Team/Edit/5 [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, TeamEditViewModel model) { if (id != model.Id) { return NotFound(); } if (ModelState.IsValid) { try { // 检查队名是否重复(排除自己) var exists = await _context.Teams .AnyAsync(t => t.Id != id && t.Name == model.Name && t.GroupId == model.GroupId); if (exists) { ModelState.AddModelError("Name", "该组别下已存在同名队别"); ViewBag.AllGroups = await _context.Groups.ToListAsync(); 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 { throw; } } catch (Exception ex) { TempData["ErrorMessage"] = $"更新失败: {ex.Message}"; ViewBag.AllGroups = await _context.Groups.ToListAsync(); return View(model); } } ViewBag.AllGroups = await _context.Groups.ToListAsync(); return View(model); } // GET: /Team/Delete/5 - 删除确认页面 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, CmbName = team.Group.Cmb.Name, SortOrder = team.SortOrder }; return View(viewModel); } catch (Exception ex) { TempData["ErrorMessage"] = $"加载删除页面失败: {ex.Message}"; return RedirectToAction(nameof(Index)); } } // POST: /Team/Delete/5 - 执行删除 [HttpPost, ActionName("Delete")] [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 (Exception ex) { TempData["ErrorMessage"] = $"删除失败: {ex.Message}"; return RedirectToAction(nameof(Delete), new { id = id }); } } private async Task<bool> TeamExists(int id) { return await _context.Teams.AnyAsync(e => e.Id == id); } } } 这是原来的代码,请在这个代码的基础上修改
10-07
// 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 } } 在这个代码修改
最新发布
10-07
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值