Asp Core 5.0 Razor 页面:如何在调用 RedirectToPage() 时保留 window.location.hash

Asp Core 5.0 Razor Page: how to preserve window.location.hash when calling RedirectToPage()

我有 Asp Core 5.0 Razor 页面,其中 table 表示例如来自数据库的消息。有几个 table 被放置在几个选项卡中 (Boostrap 4 nav-pills)。每条记录都有一个图标,用于表示修改消息的某些操作:

<a asp-page-handler="ModifyMessage" asp-route-id="@item.Id" title="Modify message"><i class="fas fa-edit"></i></a>

该操作的代码隐藏类似于:

public async Task<IActionResult> OnGetModifyMessageAsync(Int64 Id)
{
     var message = _context.Messages.Single(m => m.Id == Id);
     message.MessageIsRead = !message.MessageIsRead;

     await _context.SaveChangesAsync();

     return RedirectToPage(); //it can be Page();
}

在我的视图中,当用户更改活动标签时,将活动标签 ID 保存在 window.location.hash 中。之后我阅读 window.location.hash 并在页面重新加载时恢复活动选项卡。

window.location.hash 值在通过 F5(甚至 Ctrl+F5)和通过 JavaScript:

重新加载页面之间保留
$('#SomeButtonId').click(function (e) {
        window.location.reload();
    });

但是 window.location.hash 值在通过 return RedirectToPage();(或 return Page();)重新加载页面时被清除。

那么如何在调用RedirectToPage()时保留window.location.hash?

提前致谢。

我也遇到了导航标签的问题。我想出了一个可以接受的解决方案。您所要做的是以编程方式单击页面加载上的选项卡。 在您的 Get 方法中,将活动选项卡的 ID 传递给请求: 我不确定你是否在索引文件中有这个,但如果这个请求在 Index.cshtml.cs 中,你会重定向到 /index/id/activeTabId。请在下方评论,以便我了解您的路由设置方式。

 OnGetModifyMessageAsync(Int64 Id,activeTabId){
   
  return RedirectToPage($"/{Id}/#{activeTabId}")
}

在页面加载时的 JS 文档中,您获得 window 位置并单击带有 javascript 的选项卡:

window.onload =function(){
   let loc = window.location.href;
    if (loc.includes("#")) {
        let activeTabId = refLoc.substring(refLoc.indexOf('#') + 1, refLoc.length);
        document.getElementById(activeTabId).click();
    }
}

所以我最终以不使用asp-page-handlerasp-route-id标签而使用JavaScript/jQuery+AJAX解决方案结束:

<a title="Modify message"><i class="fas fa-edit"></i></a>

<script>
var ModifyMessage= function (messageId) {    
    $.ajax({
        type: "Get",
        url: '?handler=ModifyMessage',
        data: "messageId=" + messageId,
        async: false,
        contentType: "application/json",
        success: function () {
        },
        failure: function (response) {
            alert(response);
        },
        error: function (response) {
            alert(response);
        }
    });
}

$(document).ready(function () {
    $(".fa-edit").parent("a").click(function (e) {
        //get current message Id somehow
        var messageId= $(e.target).closest('tr')[0].children[0].innerText.trim();
        //call AJAX function           
        ModifyMessage(messageId);
        //refresh page to get all messages current state (preserves window.location.hash)
        window.location.reload();
    });
}
</script>

代码隐藏:

public JsonResult OnGetModifyMessage(Int64 messageId)
{
     var message = _context.Messages.Single(m => m.Id == messageId);
     message.MessageIsRead = !message.MessageIsRead;

     _context.SaveChanges();

     return null;
}