Is it possible to force an @Html.ActionLink()
to do a POST
instead of a GET
? If so, how?
问题:
回答1:
ActionLink
helper method will render an anchor
tag, clicking on which is always a GET
request. If you want to make it a POST
request. You should override the default behviour using a little javacsript
@ActionLink("Delete","Delete","Item",new {@id=4},new { @class="postLink"})
Now some jQuery
code
<script type="text/javascript">
$(function(){
$("a.postLink").click(function(e){
e.preventDefault();
$.post($(this).attr("href"),function(data){
// got the result in data variable. do whatever you want now
//may be reload the page
});
});
});
</script>
Make sure you have an Action
method of HttpPost
type to handle this request
[HttpPost]
public ActionResult Delete(int id)
{
// do something awesome here and return something
}
回答2:
I suppose that if you need something like that is for an Action that will be doing something "permanent" on server side. For instance, deleting an object in database.
Here is a complete example of doing a delete using a link and posting: http://www.squarewidget.com/Delete-Like-a-Rock-Star-with-MVC3-Ajax-and-jQuery
From the previous link (recomended reading anyway):
A delete link in your view:
@Ajax.ActionLink("Delete", "Delete", "Widget",
new {id = item.Id},
new AjaxOptions {
HttpMethod = "POST",
Confirm = "Are you sure you want to delete this widget?",
OnSuccess = "deleteConfirmation"
})
A bit of JS:
function deleteConfirmation(response, status, data) {
// remove the row from the table
var rowId = "#widget-id-" + response.id;
$('.widgets').find(rowId).remove();
// display a status message with highlight
$('#actionMessage').text(response.message);
$('#actionMessage').effect("highlight", {}, 3000);
}
回答3:
What I would do is wrap your html around a form
@using(Html.BeginForm("YourAction","YourController", FormMethod.Post)){
<button>Hello</button>
}
Instead of using a link you might want to use a button.
If you really want to use a link, you might need some javascript
Something like this:
$("#idOfYourLink").click(function(){
var form = $(this).parents('form:first');
form.submit();
});
回答4:
It's not possible to have a <a>
element perform a POST to a web server.
You can use Javascript to capture the click event, stop the navigation, and perform an AJAX POST to the server, but if the user has Javascript disabled nothing will happen.
Do you have to use a <a>
element, or just something that resembles a <a>
element?
Also worth mentioning is to have a look at AjaxLink
. It allows you to easily use a <a>
element to perform an AJAX POST.
回答5:
If you think... there is no tag for link in HTML that does a POST. And that's why you can't force a link to do a POST (and it doesn't make any sense). To use "POST", ou should "POST" something. And that something should be a form, or you can do a POST using a javascript function for AJAX. Anyway, if you need to POST without post anything you should review your resourcemodel, something stinks.