243

I know this isn't right, but for the sake of illustration I'd like to do something like this:

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

My goal is to make an HTML button that will call my MVC controller's action method.

2
  • 5
    Define "call." This could mean an AJAX call, a link to another page, or posting a form, to name a few possibilities. Commented Mar 23, 2010 at 22:03
  • Most answers above might already have worked, unfortunately none worked for me. I found here a useful answer from another Stackoverflow post! It worked for me on ASP with dot net framework 4.7 mvc5 and bootstrap version 3.* and of course in Razor View. The main purpose of the question as I assume is to show a link that looks like a button. Commented May 16, 2019 at 15:47

19 Answers 19

302

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") %>'" />
Sign up to request clarification or add additional context in comments.

7 Comments

I used this suggestion because it doesn't require a form. Thank you!
may wrap it in an HtmlHelper something like public static string ActionButton(this HtmlHelper helper, string action, string controller, string text) { return String.Format("<input type=\"button\" value=\"{0}\" onclick=\"location.href='{1}' />",text,Url.Action(action,controller)); }
it gives unterminated string constant error in my code
If you want to pass a parameter with that, you can use <input type="button" value="Go Somewhere Else" onclick="location.href='<%: Url.Action("Action", "Controller", new { parameter1 = value1 }) %>'" />
<input type="button" value="DeleteAll" onclick="location.href='@Url.Action("DeleteAll", "Home")'" />
|
290

Razor syntax is here:

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

7 Comments

I still got an "unterminated string constant" error in the IDE which still didn't render properly. I had to use solution from here: stackoverflow.com/a/16420877/410937
@atconway -- strange, it worked for me exactly how this answer presents it. VS2013.
@atconway -- had the same error but changed changed the tag from 'input' to 'button' and that resolved the error.
With Parameters <input type="button" title="Delete" value="D" onclick="location.href='@Url.Action("Delete", "movies", new { id = item.ID })'" />
in my case just using <button type="button" class="btn btn-primary" onclick="location.href='@Url.Action("action", "controller")'" >Go Somewhere Else</button> did the trick
|
98
<button type="button" onclick="location.href='@Url.Action("MyAction", "MyController")'" />

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

Comments

22

Try this:

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

This should work for you.

2 Comments

you can also use bootstrap or other css classes like this: @Html.ActionLink("DisplayText", "Action", ["Controller"], routeValues: null, htmlAttributes: new {@class="btn btn-info btn-md", style="white-space: normal" })
@Asaf solution worked for me by removing the [] around "Controller"
16

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")'" />

Comments

15

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>

Comments

11

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

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

Comments

11

Of all the suggestions, nobdy used the razor syntax (this is with bootstrap styles as well). This will make a button that redirects to the Login view in the Account controller:

    <form>
        <button class="btn btn-primary" asp-action="Login" asp- 
   controller="Account">@Localizer["Login"]</button>
    </form>

3 Comments

Interestingly, I had to remove: type="button" for this to work correctly.
Did you look at the date? Question was posted years before tag helpers were a thing.
Yes, but since I ended up here searching for an answer, years later. I thought I would post a more modern answer for others in my situation.
8

it's better use this example

<a href="@Url.Action("Register","Account", new {id=Item.id })"
class="btn btn-primary btn-lg">Register</a>

Comments

6

Despite onclick Method you can also use formaction as follows:

<button type="submit" id="button1" name="button1" formaction='@Url.Action("Action", "Controller")'>Save</button>

1 Comment

This works better if you have an action with an HttpPost verb attribute it will stop web crawlers from visiting those destructive links (thanks to Hector Correa for this info)
5

The HTML <button> element can only postback to the form containing it.

Therefore, you need to make a form that POSTs to the action, then put a <button> or <input type="submit" /> in the form.

2 Comments

Downvote reason, answer is wrong. <button formaction="/anotherurl" > works fine.
@NickG that is the proper way. Thank you! It surprises me, that from what I saw - ajax call is recommended by most. But then all advantages of .net are lost. My particular case required persisting TempData/ViewBag
5

So, I'm using Razor but this will work using either. I'm basically wrapping a button in a link.

<a href="Controller/ActionMethod">
    <input type="button" value="Click Me" />
</a>

Comments

5

Use this example :

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

Comments

4

In case if you are getting an error as "unterminated string constant", use the following razor syntax :

<input type="button" onclick="@("location.href='"+ Url.Action("Index","Test")+ "'")" />

Comments

4

When you implement the action in the controller, use

return View("Index");

or

return RedirectToAction("Index");

where Index.cshtml (or the page that generates the action) page is already defined. Otherwise you are likely encountering "the view or its master was not found..." error.

Source: https://blogs.msdn.microsoft.com/aspnetue/2010/09/17/best-practices-for-asp-net-mvc/

Comments

1

If you are in home page ("/Home/Index") and you would like to call Index action of Admin controller, following would work for you.

<li><a href="/Admin/Index">Admin</a></li>

Comments

1

it's better use this example.

Call action and controller using a ActionLink:

@Html.ActionLink("Submit", "Action", "Controller", route, new { @class = "btn btn-block"})

Comments

0

OK, you basically need to pass the action to the button and call it when click happens, it doesn't need to be inside a from, you can use HTML onclick on button to trigger it when the button get clicked...

<button id="my-button" onclick="location.href='@Url.Action("YourActionName", "YourControllerName")'">Submit</button>

Comments

0

You can always play around with htmlHelpers and build some stuff

    public static IHtmlContent BtnWithAction(this IHtmlHelper htmlHelper, string id, string text, string css="", string action="", string controller="")
    {
        try
        {
            string str = $"<button id=\"{id}\" class=\"{css}\" type=\"button\" ###>{text}</button>";
            if (!string.IsNullOrEmpty(action) && !string.IsNullOrEmpty(controller))
            {                    
                string url = ((TagBuilder)htmlHelper.ActionLink("dummy", action, controller)).Attributes["href"];
                var click = !string.IsNullOrEmpty(url) ? $"onclick=\"location.href='{url}'\"" : string.Empty;
                return new HtmlString(str.Replace("###", click));
            }
            return new HtmlString(str.Replace("###", string.Empty));
        }
        catch (Exception ex)
        {
            Log.Error(ex, ex.Message);
            var fkup = "<script>alert(\"assumption is the mother of all failures\")</script>";
            return new HtmlString(fkup);
        }
    }

And then on the view call it like this

@Html.BtnWithAction("btnCaretakerBack", "Back", "btn btn-primary float-right", "Index", "Caretakers")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.