I have Asp Core 5.0 Razor Page with a table that represents for example Messages from database. There are several tables that are placed inside several tabs (Boostrap 4 nav-pills). Each record has a icon for some action that modify a message:
<a asp-page-handler="ModifyMessage" asp-route-id="@item.Id" title="Modify message"><i class="fas fa-edit"></i></a>
Code-behind for that action looks something like:
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();
}
On my View is save active tab Id in window.location.hash when user changes active tab. Afterwards I read window.location.hash and restore active tab on page reload.
window.location.hash value is preserved between page reloads via F5 (or even Ctrl+F5) and via JavaScript:
$('#SomeButtonId').click(function (e) {
window.location.reload();
});
But window.location.hash value is cleared when page reloads via return RedirectToPage();
(or return Page();
).
So howto preserve window.location.hash when calling RedirectToPage()?
Thank you in advance.
So I finally ended with not using asp-page-handler
and asp-route-id
tags and using JavaScript/jQuery + AJAX solution:
<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>
Code-behind:
public JsonResult OnGetModifyMessage(Int64 messageId)
{
var message = _context.Messages.Single(m => m.Id == messageId);
message.MessageIsRead = !message.MessageIsRead;
_context.SaveChanges();
return null;
}