ASP.Net Core 2.1 MVC分页局部视图点击后跳转登录页问题求助
从你的描述和代码来看,问题出在身份验证拦截、按钮行为冲突以及一处大小写拼写错误上,导致点击按钮后出现局部视图短暂显示随即跳转登录页的情况,具体解决步骤如下:
1. 修复AntiForgery Token缺失问题
ASP.NET Core中,带有[HttpPost]特性的Action默认会启用AntiForgery验证(尤其是在启用身份验证的项目中)。你的表单里没有添加防伪令牌,导致Post请求被框架拦截,触发登录跳转。
修改视图中的form代码,添加防伪令牌:
<form asp-controller="Employ" asp-action="Employees" data-ajax="true" data-ajax-method="post" data-ajax-mode="replace" data-ajax-update="#EmployList"> @Html.AntiForgeryToken() <!-- 新增这一行 --> <input type="hidden" id="CurrentPage" value="@ViewBag.CurrentPage"/> <input type="hidden" id="LastPage" value="@ViewBag.LastPage"/> </form>
同时,确保你的Post Action上没有禁用AntiForgery验证(无特殊需求的话保持默认即可)。
2. 移除按钮上的跳转属性冲突
你的按钮上添加了asp-controller和asp-action属性,这会让Razor生成一个Get请求的跳转链接。点击按钮时会同时触发两种行为:
- 脚本触发的form AJAX Post提交
- 按钮本身的Get跳转
这就导致局部视图短暂加载后,页面立刻跳转到登录页(因为Get请求可能未通过身份验证,或直接触发了默认Action跳转)。
修改按钮代码,移除这些属性:
<div> <button id="Next"> Next </button> <button id="Previous"> Previous </button> </div>
3. 修正脚本中的大小写拼写错误
你的脚本里写的是$("#lastPage").val(),但对应的input id是LastPage(首字母大写),这会导致无法正确获取最后一页的值,分页逻辑可能出错。
修改脚本中的选择器:
function CalculateAndSetPage(movingType){ var currentPage = parseInt($("#CurrentPage").val()); var lastPage = parseInt($("#LastPage").val()); // 把lastPage改成LastPage if(currentPage == 1 && movingType == "Previous") return false; if(currentPage==lastPage && movingType=="Next") return false; if (movingType == "Previous") currentPage--; if (movingType == "Next") currentPage++; $("#CurrentPage").val(currentPage); return true; }
4. 额外修正Controller的拼写错误
你的Post Action返回值写成了IActionResults,多了个s,应该是IActionResult:
[HttpPost] public IActionResult Employees(int CurrentPage, int LastPage) { // 修正IActionResults为IActionResult ViewBag.CurrentPage = CurrentPage; ViewBag.LastPage = LastPage; var value = _context.Employee.ToList(); return PartialView("_EmployeeList", value.OrderBy(c=>c.Id).Skip((CurrentPage - 1)*4).Take(4)); }
验证效果
做完以上修改后,点击Next/Previous按钮时,只会触发form的AJAX Post请求,框架验证防伪令牌通过后返回局部视图,替换指定的#EmployList区域,不会再出现跳转登录页的情况。
内容的提问来源于stack exchange,提问作者Morse Code




