ASP.NET MVC中如何向@Html.Partial传递ID或获取Session ID
问题解决:Partial调用视图空引用+Session/ID传递失败
核心问题原因
直接用@Html.Partial调用视图时,不会触发对应Controller的Action方法,导致Index视图的Action里的Session读取、ViewBag赋值、数据查询逻辑完全没执行,视图依赖的Model或ViewBag数据为空,进而抛出空引用错误。
解决方案步骤
1. 替换Partial为Action调用
把Dashboard页面里的@Html.Partial改成@await Html.RenderActionAsync(因为你的Index是异步Action),这样会触发Controller的Index方法,执行所有逻辑:
@* For more information on enabling MVC for empty projects, visit *@ @{ } <!doctype html> <html lang="en"> @await Html.RenderActionAsync("Index", "MaidProfileModels") <p>Something very important here</p> </div> </html>
2. 修正Index Action的ID获取逻辑
原来的Index强制要求传入int id,但实际应该优先从Session取ID,避免参数缺失导致错误:
// GET: MaidProfileModels public async Task<IActionResult> Index(int? id) { // 优先用传入的ID,没有则取Session里的MaidID var maidId = id ?? HttpContext.Session.GetInt32("MaidID"); // 校验ID是否存在,避免后续空引用 if (maidId == null) { // 无ID时跳转到登录或其他处理页面 return RedirectToAction("Login", "Account"); } var online_Maid_FinderContext = _context.MaidProfile .Where(i => i.MaidID.Equals(maidId.Value)) .Include(m => m.Address) .Include(m => m.Login); return View(await online_Maid_FinderContext.ToListAsync()); }
3. 确保Session功能正常启用
如果是.NET Core项目,必须在Startup.cs里配置Session:
- 在
ConfigureServices方法中添加:services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(30); // 设置Session超时时间 options.Cookie.HttpOnly = true; options.Cookie.IsEssential = true; }); - 在
Configure方法中添加(要放在app.UseRouting()之后,app.UseAuthorization()之前):app.UseSession();
4. 优化Session设置后的跳转逻辑
设置Session后的跳转不需要额外传ID,直接依赖Session即可:
HttpContext.Session.SetInt32("MaidID", cs.MaidID); // 不需要传cs.MaidID,Session已保存该值 return RedirectToAction("MaidDashboard", "MaidProfileModels");
内容的提问来源于stack exchange,提问作者bs180201421 MUHAMMAD SHADAB SK
相关产品推荐
相关产品推荐

