1

I use mvc 5 in my project.

I create action link using razor that sent some data to action method by GET mthod.

Here is action link:

<tbody>
    @foreach (var item in Model)
         {
               <tr><td>@Html.ActionLink(item.Name, "About", "Home", item, new { @class = "btn btn-featured btn-white height-30 width-100" })</td></tr>
         }
 </tbody>

My question is how to change created action link above to make it sent data by POST to action method?

Michael
  • 13,950
  • 57
  • 145
  • 288
  • 3
    `ActionLink` helper always use `GET` because it generates anchor tag. If you want to perform POST request, use `jQuery.ajax()` or normal form submit instead. – Tetsuya Yamamoto Sep 25 '18 at 07:09
  • 1
    A link makes a GET. If you want a POST, then use a form and submit it –  Sep 25 '18 at 07:09
  • Or you can handle the `click` event and use `fetch` or `$.ajax()` in the event handler to make a POST request – Panagiotis Kanavos Sep 25 '18 at 07:14

1 Answers1

0

You are using an HTML Anchor Link, which always do a GET action from Browser.

If your requirement is to do a post, you can use one of the below approaches:

1. Ajax Post

@Ajax.ActionLink("About", "Home", new { id = "myForm", @class = "btn btn-featured btn-white" }, new AjaxOptions { HttpMethod = "POST" })

For using @Ajax you will need to add a nuget reference from: https://www.nuget.org/packages/Microsoft.jQuery.Unobtrusive.Ajax/

This will add new scripts to your project (jquery.unobtrusive-ajax.min.js)

Without this, it will continue to use GET as your Method.

2. Form Submit Post

@using (Html.BeginForm("About", "Home", FormMethod.Post, new { id = "myForm", @class = "btn btn-featured btn-white" }))
{
   <a href="javascript:document.getElementById('myForm').submit()">
      <span>Submit</span>
   </a>
}
Habeeb
  • 7,601
  • 1
  • 30
  • 33
  • I tried it: @Ajax.ActionLink(item.Name, "About", "Home", item, new AjaxOptions { HttpMethod = "POST" }, new { @class = "btn btn-featured btn-white height-30 width-100" }) But when I look at fiddler it shows GET request – Michael Sep 25 '18 at 07:20
  • And where do I put foreach? – Michael Sep 25 '18 at 07:25
  • @Michael assuming i have understood correctly, inside the `using`, and the `` will go inside the `foreach` – WhatsThePoint Sep 25 '18 at 07:35
  • Note about `@Ajax.ActionLink` helper: https://stackoverflow.com/questions/22420512/ajax-actionlink-is-using-get-instead-of-post. Also it may necessary to use `preventDefault()` before using `submit()` function. – Tetsuya Yamamoto Sep 25 '18 at 07:36
  • @Michael - I have updated the answer. Please add reference to nuget package https://www.nuget.org/packages/Microsoft.jQuery.Unobtrusive.Ajax/ – Habeeb Sep 25 '18 at 07:41
  • Habeeb, thanks for post.In your example Form Submit Post how do I POST object to action method? in my case the object is item – Michael Sep 25 '18 at 11:19