user469652
user469652

Reputation: 51291

Use normal HTML Button to call Controller in ASP.NET MVC2?

I want to use normal HTML Button to call Controller in ASP.NET MVC2, instead of ActionLink, is that possible?

Upvotes: 3

Views: 3492

Answers (3)

Garry Shutler
Garry Shutler

Reputation: 32698

<form method="get" action="YourUrl">
    <button type="submit">Click me</button>
    <input type="submit" value="Or click me" />
</form>

You will probably want to use the <%= Url.Action(...) %> helper methods to determine the action URL for the form.

This requires no javascript to function but will get the appearance you are looking for. The button tags can be styled a bit more that the input type but it depends what existing styles you might have as to which one you use. They are functionally identical.

Upvotes: 1

tvanfosson
tvanfosson

Reputation: 532545

Typically with a button, you'll either use javascript to invoke the action or wrap it in a form (or both).

<% Html.BeginForm( "action", "controller", new { id = Model.ID } )
   { %>
     <button type="submit">Go</button>
<% } %>

<script type="text/javascript">
    $(function() {
         $('button').click( function() {
              var form = $('form');
              $.post( form.attr('action'), form.serialize(), function(msg) {
                    alert(msg);
              });
              return false; // don't really submit the form
         });
    });
</script>

Upvotes: 3

Gideon
Gideon

Reputation: 18491

Sure, just use Url.Action() to render the URL to the action.

<a href="<%= Url.Action("Action") %>">BLA BLA</a>

or

<button onclick="javascript: window.location = '<%= Ajax.JavascriptEncode(Url.Action("Action")) %> '">Click me</button>

Upvotes: 4

Related Questions