tha*_*ssd 5 asp.net asp.net-mvc asp.net-core razor-pages
我有一个 ASP.NET Core razor 页面和模型,它使用查询字符串来过滤搜索结果并通过 GET 进行分页。
考虑用户执行搜索以到达此页面:
https://localhost/Users?searchBy=Name&searchTerm=test&resultPage=2
现在,在结果页面上,我有一个通过弹出模式执行删除的按钮。当用户单击删除时,它会 POSTS 到页面处理程序OnPostDelete()。asp-page-handler我为此使用标签助手:
<button asp-page-handler="Delete" asp-route-id="@Model...">
删除后,我希望用户被重定向回与之前完全相同的 URL,因此他/她保留在相同的结果页面上,而不是被重定向到普通索引页面。
所以我的问题是如何在整个帖子和重定向过程中轻松地保留这些查询字符串?目前这是我正在做的事情:
在删除弹出模态剃刀页面上,我使用这些代码来捕获当前查询字符串:(我不知道如何直接转换Context.Request.Query为 a Dictionary)
@{
Dictionary<string, string> query = new Dictionary<string, string>();
foreach (var queryString in Context.Request.Query)
{
query.Add(queryString.Key, queryString.Value);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,我将查询添加到asp-all-route-data删除按钮上的标签助手:
<button asp-page-handler="Delete" asp-all-route-data="query" asp-route-id="@Model...">
这使得标签助手生成的结果formaction属性包含 POST URL 中的查询字符串。
然后在我的页面处理程序的OnPostDelete()方法中,我再次重新捕获查询字符串,在重定向之前删除由删除按钮添加的不需要的字符串(id 等):
Dictionary<string, string> query = new Dictionary<string, string>();
foreach (var queryString in HttpContext.Request.Query)
{
if ((queryString.Key != "id") && (queryString.Key != "handler"))
{
query.Add(queryString.Key, queryString.Value);
}
}
return RedirectToPage($"Index",query);
Run Code Online (Sandbox Code Playgroud)
它有效,但看起来很乏味。我是这方面的新手,我确信有更好的方法来做到这一点。我们将非常感谢您的帮助。
这可以用更简单的方式解决。
添加
<input type="hidden" asp-for="ReturnUrl" value="@Request.GetEncodedPathAndQuery()" />
Run Code Online (Sandbox Code Playgroud)
您的表单现在可能如下所示
<form method="post">
<input type="hidden" asp-for="ReturnUrl" value="@Request.GetEncodedPathAndQuery()" />
<button type="submit" asp-page-handler="Delete" asp-route-id="1">Button 1</button>
<button type="submit" asp-page-handler="Delete" asp-route-id="2">Button 2</button>
</form>
Run Code Online (Sandbox Code Playgroud)
或者,如果每个按钮都有一个表单
<form method="post"
asp-page-handler="Delete"
asp-route-id="1"
asp-route-returnUrl="@Request.GetEncodedPathAndQuery()">
<button type="submit">Button 1</button>
</form>
<form method="post"
asp-page-handler="Delete"
asp-route-id="2"
asp-route-returnUrl="@Request.GetEncodedPathAndQuery()">
<button type="submit">Button 2</button>
</form>
Run Code Online (Sandbox Code Playgroud)
在 Razor 页面代码隐藏中,添加
[BindProperty]
public string ReturnUrl { get; set; }
Run Code Online (Sandbox Code Playgroud)
在 POST 请求结束时:
return Redirect(ReturnUrl);
Run Code Online (Sandbox Code Playgroud)
以上代码是在我的电脑上测试和验证的。
这是登录过程中经常使用的模式:
| 归档时间: |
|
| 查看次数: |
3914 次 |
| 最近记录: |