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
因此,您需要制作一个表单,将其发布到操作中,然后在表单中放入一个
如果出现"未终止的字符串常量"错误,请使用以下剃刀语法:
1 | <input type="button" onclick="@("location.href='"+ Url.Action("Index","Test")+"'")" /> |
最好使用这个例子
1 2 | <a href="@Url.Action("Register","Account", new {id=Item.id })" class="btn btn-primary btn-lg">Register |
在控制器中实施操作时,请使用
1 | return View("Index"); |
要么
1 | return RedirectToAction("Index"); |
其中已经定义了Index.cshtml(或生成操作的页面)页面。否则,您可能会遇到"未找到该视图或其主视图..."的错误。
来源:https://blogs.msdn.microsoft.com/aspnetue/2010/09/17/best-practices-for-asp-net-mvc/
尽管使用了onclick方法,您也可以按以下方式使用formaction:
1 | <button type="submit" id="button1" name="button1" formaction='@Url.Action("Action","Controller")'>Save</button> |
因此,我正在使用Razor,但是无论使用哪种方法都可以。我基本上是在链接中包装一个按钮。
1 | <input type="button" value="Click Me" /> |
如果您位于主页(" / Home / Index")中,并且希望调用Admin控制器的Index操作,则可以执行以下操作。
1 2 3 | <li> Admin </li> |
好的,您基本上需要将操作传递给按钮并在单击发生时调用它,它不需要在from内,您可以在按钮上使用HTML
1 | <button id="my-button" onclick="location.href='@Url.Action("YourActionName","YourControllerName")'">Submit</button> |
使用以下示例:
1 | <button name="nameButton" id="idButton" title="your title" class="btn btn-secondary" onclick="location.href='@Url.Action("Index","Controller" new { id = Item.id })';return false;">valueButton</button> |
最好使用这个例子。
使用
1 | @Html.ActionLink("Submit","Action","Controller", route, new { @class ="btn btn-block"}) |