3

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

3 Answers 3

4

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

2 Comments

Please don't embed your javascript in a tag. It's a bad/hard to maintain practice. Note also that this won't work if javascript is turned off or you have an javascript error on the page.
I know this, but just showed it as an example. He said ActionLink (an A element) , but also mentioned HTML button (a BUTTON element) . So for completeness sake, I added both.
3

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>

2 Comments

You can specify the method of the form to be get and then give a type for the button of submit. Then you need no javascript at all.
@Garry -- it's just an example to demonstrate. Likely I'd do some sort of validation or something with AJAX instead with the javascript, but I wanted something simple. Nice to note that there are better ways of accomplishing it, though. I should have specified the type, though. IE probably wouldn't react properly in the absence of javascript without it. Good catch.
1
<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.

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.