Is it possible to force an @Html.ActionLink()
to do a POST
instead of a GET
? If so, how?
The Lookup method's arguments match the named properties in the ActionLink. MVC4 allows you to pass the model automatically through URL variables, which is seen my second example. The docs for ActionLink show that none of that method's overloads accepts a viewmodel object.
ActionLink is rendered as an HTML Anchor Tag (HyperLink) and hence it produces a GET request to the Controller's Action method which cannot be used to submit (post) Form in ASP.Net MVC 5 Razor. Hence in order to submit (post) Form using @Html. ActionLink, a jQuery Click event handler is assigned and when the @Html.
HTTPGet method creates a query string of the name-value pair whereas HTTPPost method passes the name and value pairs in the body of the HTTP request. 3. HTTPGet request has limited length and mostly it is limited to 255 characters long whereas HTTPPost request has no maximum limit.
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
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With