如何在RedirectToPage跳转时传递URL片段?
问题:如何在跳转页面时传递URL片段?
我无法为RedirectToPage操作添加URL片段。如果将"#"作为字符串的一部分添加,它会被转换为%23,导致无法正常使用。
PostAction代码
public async Task<IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return Page(); } _context.Attach(AnagraficaClientiContatti).State = EntityState.Modified; try{ await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!AnagraficaClientiContattiExists( AnagraficaClientiContatti.AnagraficaClientiContattiID)) { return NotFound(); } else { throw; } } return RedirectToPage( "../Index", new { id = Request.Query["idmaster"], pgm = Request.Query["pgm"], pgs1 = Request.Query["pgs1"], activetab = Request.Query["activetab"], searchstring = Request.Query["searchstring"] } ); }
这段代码运行正常,但我需要跳转到上述页面时在末尾加上"#specificsection"。
我尝试修改调用代码:
return RedirectToPage( "../Index", new { id = Request.Query["idmaster"], pgm = Request.Query["pgm"], pgs1 = Request.Query["pgs1"], activetab = Request.Query["activetab"], searchstring = Request.Query["searchstring"] + "#specificsection" } );
但浏览器返回的URL中#被替换成了%23,格式如下:
?id=20&pgm=2&pgs1=2&activetab=custom-tabs-one-contatti&searchstring=text%23specificsection
我也尝试按照文档说明,将片段作为第三个或第四个参数(第三个参数设为null)传递给RedirectToPage,但也没有成功。
请问有人能帮我找出问题所在吗?
提前感谢。
Best
Massimo
解决方案
你需要使用RedirectToPage的重载版本,其中专门有一个参数用于指定URL片段(锚点)。正确用法是将路由参数作为第二个参数,片段作为第三个参数传入:
return RedirectToPage( "../Index", new { id = Request.Query["idmaster"], pgm = Request.Query["pgm"], pgs1 = Request.Query["pgs1"], activetab = Request.Query["activetab"], searchstring = Request.Query["searchstring"] }, fragment: "specificsection" );
如果你的框架版本不支持具名参数,也可以按位置传递:
return RedirectToPage( "../Index", new { id = Request.Query["idmaster"], pgm = Request.Query["pgm"], pgs1 = Request.Query["pgs1"], activetab = Request.Query["activetab"], searchstring = Request.Query["searchstring"] }, "specificsection" );
注意:
- 片段参数不需要加
#,框架会自动为你添加 - 之前的错误是因为把片段拼接到了查询参数里,导致
#被URL编码成%23,这是查询参数的正常编码行为,而片段应该是独立于查询参数的URL部分
这样生成的URL会是:../Index?id=20&pgm=2&pgs1=2&activetab=custom-tabs-one-contatti&searchstring=text#specificsection,符合你的需求。
内容的提问来源于stack exchange,提问作者Max
相关产品推荐
相关产品推荐

