3

I am really bummed out that I can't figure out this simple problem even after hours of research:

@Ajax.ActionLink("Test", "Test", new AjaxOptions { HttpMethod = "Post" })

<a data-ajax="true" data-ajax-method="Post" href="/Home/Test">Test</a>

It's as simple as it can get but it makes a GET request to /Home/Test even though I specified POST.

Inside _Layout.cshtml I have

<body>

@RenderBody()

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)

</body>

The bundle jquery val includes

jquery.validate.js
jquery.validate.unobtrusive.js
allenylzhou
  • 1,431
  • 4
  • 19
  • 36
  • Perhaps: http://stackoverflow.com/questions/12520694/mvc3-razor-ajax-actionlink-wont-use-post-method – Brian Mar 15 '14 at 08:04
  • As the duplicate says you are missing a reference for the `jquery.unobtrusive-ajax.js` – nemesv Mar 15 '14 at 11:53
  • @Brian I'd like to note that while the source of the problem is the same, that answer refers to a MVC 3 project while I am using MVC 4 project. The versions of jQuery that comes with these projects are different and there are some subtleties that need to be resolved which the other answers do not address. I solved the problem and I will edit the question and write my own answer right now. – allenylzhou Mar 15 '14 at 20:02
  • @nemesv what is the difference between jquery.validate.unobtrusive.js and jquery.unobtrusive-ajax.js? – allenylzhou Mar 15 '14 at 20:03
  • @allenylzho validate is for validation of fields(Limits, Required, Number, etc). ajax is for making forms and other items send via AJAX. – Brian Mar 15 '14 at 20:11

1 Answers1

7

Usually when you want to submit data you use a form and a submit button. In my opinion it's not a good idea to use POST method on an action link.

Try using @Ajax.BeginForm(...){}.

And before you do this, make sure you have enabled <add key="UnobtrusiveJavaScriptEnabled" value="true" /> in your web.config. After you check this, open your web application and look at the source code an make sure you have the following files included:

<script src="∼/Scripts/jquery-1.10.2.js"></script>
<script src="∼/Scripts/jquery.unobtrusive-ajax.js"></script>

Make sure also that your browser has Javascript enabled.

If none of this solves your problem, try adding the url to the options:

@Ajax.ActionLink("Test", "Test", new AjaxOptions { HttpMethod = "Post", Url = Url.Action("Test") })

This is a fallback for the cases in either the user has Javascript disabled, either you missed the reference to jquery.unobtrusive-ajax.js.

tzortzik
  • 4,993
  • 9
  • 57
  • 88
  • thank you for the answer and suggestions. It is correct but I am going to write my own answer because there are some extra things I had to tweak in my project settings in order to resolve my particular problem. – allenylzhou Mar 15 '14 at 20:04
  • fixed my problem. – Rm558 Sep 07 '16 at 20:00