Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML button calling an MVC Controller and Action method

People also ask

What is HTML ActionLink in MVC?

Html. ActionLink creates a hyperlink on a view page and the user clicks it to navigate to a new URL. It does not link to a view directly, rather it links to a controller's action.


No need to use a form at all unless you want to post to the action. An input button (not submit) will do the trick.

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

Razor syntax is here:

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

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

type="button" prevents page from submitting. instead it performs your action.


Try this:

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

This should work for you.


You can use Url.Action to specify generate the url to a controller action, so you could use either of the following:

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

or:

<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>

This is how you can submit your form to a specific controller and action method in Razor.

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

Building on couple of the above answers, you could do this:

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