关于asp.net mvc:HTML按钮调用MVC控制器和Action方法

HTML button calling an MVC Controller and Action method

我知道这是不对的,但是为了说明起见,我想做这样的事情:

1
<%= Html.Button("Action","Controller") %>

我的目标是制作一个HTML按钮,该按钮将调用我的MVC控制器的action方法。


除非您要张贴到操作中,否则根本不需要使用表格。输入按钮(不提交)可以解决问题。

1
2
3
  <input type="button"
         value="Go Somewhere Else"
         onclick="location.href='<%: Url.Action("Action","Controller") %>'" />


剃刀语法在这里:

1
<input type="button" value="Create" onclick="location.href='@Url.Action("Create","User")'" />


1
<button type="button" onclick="location.href='@Url.Action("MyAction","MyController")'" />

type =" button"阻止页面提交。而是执行您的操作。


尝试这个:

1
@Html.ActionLink("DisplayText","Action","Controller", route, attribute)

这应该为您工作。


您可以使用Url.Action指定生成控制器操作的url,因此可以使用以下任一方法:

1
2
3
<form method="post" action="<%: Url.Action("About","Home") %>">
   <input type="submit" value="Click me to go to /Home/About" />
</form>

要么:

1
2
3
4
<form action="#">
  <input type="submit" onclick="parent.location='<%: Url.Action("About","Home") %>';return false;" value="Click me to go to /Home/About" />
  <input type="submit" onclick="parent.location='<%: Url.Action("Register","Account") %>';return false;" value="Click me to go to /Account/Register" />
</form>


基于以上几个答案,您可以执行以下操作:

1
<button onclick="location.href='@Url.Action("ActionName","ControllerName")'" />


这样可以将表单提交到Razor中的特定控制器和操作方法。

1
 <input type="submit" value="Upload" onclick="location.href='@Url.Action("ActionName","ControllerName")'" />

HTML