I want to use normal HTML Button to call Controller in ASP.NET MVC2, instead of ActionLink, is that possible?
3 Answers
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>
2 Comments
tvanfosson
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.
Gideon
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.
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
Garry Shutler
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.tvanfosson
@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.
<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.