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?
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>
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>
<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.
精彩评论