单击按钮时如何重定向用户?

Den*_*ail 54 asp.net-mvc

我有一个带按钮的视图.当用户单击按钮时,我希望将它们重定向到数据输入视图.我该如何做到这一点?我应该提到创建,测试和运行的视图.我可以通过输入网址找到他们.

我找到了解释如何连接按钮的onclick事件的步骤,但我是MVC的新手,有点丢失了.

谢谢!

Dar*_*rov 88

这取决于按钮的含义.如果是链接:

<%= Html.ActionLink("some text", "actionName", "controllerName") %>
Run Code Online (Sandbox Code Playgroud)

要发布,您可以使用表单:

<% using(Html.BeginForm("actionName", "controllerName")) { %>
    <input type="submit" value="Some text" />
<% } %>
Run Code Online (Sandbox Code Playgroud)

最后,如果你有一个按钮:

<input type="button" value="Some text" onclick="window.location.href='<%= Url.Action("actionName", "controllerName") %>';" />
Run Code Online (Sandbox Code Playgroud)


AGu*_*ald 35

作为其他答案的补充,这里是剃刀引擎语法:

<input type="button" value="Some text" onclick="@("window.location.href='" + @Url.Action("actionName", "controllerName") + "'");" />
Run Code Online (Sandbox Code Playgroud)

要么

window.location.href = '@Url.Action("actionName", "controllerName")';
Run Code Online (Sandbox Code Playgroud)


小智 8

如果使用JQuery,你可以这样做:

<script type="text/javascript">
    $('#buttonid').click(function () {
        document.location = '@Url.Action("ActionName","ControllerName")';
    });
</script>
Run Code Online (Sandbox Code Playgroud)


Dus*_*ine 7

如果像我一样,你不喜欢依赖JavaScript来获取按钮上的链接.您还可以使用锚点并使用CSS将其设置为类似按钮的样式.

<a href="/Controller/View" class="Button">Text</a>
Run Code Online (Sandbox Code Playgroud)