如何创建一个按钮,当点击后跳转到 Razor 页面(在 dotnet core 2 中的 Razor 页面)

5

我可以使用锚点标签助手从一个现有的razor页面跳转到另一个razor页面,例如:

<a asp-page="./EditReport" asp-route-id="@report.IntegrityReportId" class="btn fa fa-edit"></a>

我该如何使用一个按钮来实现与此类似的功能。 我已经尝试过:

<button type="button" asp-route-data="@report.IntegrityReportId" asp-route="EditReport">EditReport</button>

但是网页始终无法加载。我还尝试使用页面处理程序并尝试了不同的变体:
<input type="button" asp-page-handler="EditReport" asp-route="@report.IntegrityReportId"/>

并且相关联的(在页面cs文件中):

public ActionResult OnEditReport(int id)
        {
            return RedirectToPage("./EditReport", id);
        }

但是这个方法从来没有被调用过(我也尝试过将方法命名为OnPostEditReport,但是问题依旧)。
如果有帮助的话,我的原始非.NET Core应用程序可以正常工作:
<button type="button" title="Edit report" class="btn btn-datatable fa fa-edit" onclick="location.href = '@Url.Action("EditReport", "Home", new {id = report.IntegrityReportID})'"></button>

非常感谢您的帮助。谢谢。

6个回答

7
我使用下面的锚点来达到我需要的效果 - 这样它看起来像一个按钮。
<a asp-page="./EditReport" asp-route-id="@report.IntegrityReportId" class="btn btn-default"><i class="fa fa-edit"></i></a>

4
以下解决方案适用于我的ASP.NET Core 3.1项目:
``` 编辑 ```
上面突出显示的代码在一行上,只是Stack Overflow展示答案的方式。请注意,我选择在按钮文本之前显示图标,然后我在按钮标签“编辑”之前添加了一个单个字符空格,以使按钮看起来更好看。

3

如果没有使用JavaScript,你无法仅仅使用一个按钮来重定向到另一个 Razor 页面。你需要在表单标签内使用提交按钮来实现重定向到另一个 Razor 页面。以下示例演示了如何进行 GET 重定向并重定向到“关于”页面:

<form method="get">
    <button type="submit" asp-page="./About">Click me to go to the About page</button>
</form>

如果您想发起一个POST请求,请使用以下代码:

<form method="post">
    <button type="submit" asp-page="./About">Click me to go to the About page</button>
</form>

在这两种情况下,您可以定义路由值或处理程序以满足要求。希望对您有所帮助。

谢谢pitaridis,但我仍然无法让它工作。页面看起来像是在做某些事情,但然后原始页面再次显示出来。你会如何用JavaScript实现呢?你知道为什么我们需要在JavaScript中这样做和/或为什么这与标准MVC不同,我可以只使用formaction吗?非常感谢。 - Blingers

0

我知道已经晚了一年,但你必须删除 'type="button"',同时尝试从 asp-page="./EditReport" 中删除 '.'。 敬礼。


0

使用按钮:

<button type="button" class="btn" onclick="window.location.href = '/YourPage'">Button Title</button>

0

这在ASPNET Core 3.1中有效。

<form method="get" action="/myRazorPage">
    <button type="submit">Join Now</button>
</form>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接