MVC Ajax.ActionLink doesn't find POST method
Asked Answered
B

4

13

I have a POST method declared in my controller:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UpdateComments(int id, string comments)
{
    // ... 
}

and an ActionLink in my view:

<%= Ajax.ActionLink("update", "UpdateComments", 
                        new { id = Model.Id, comments = "test" }, 
                        new AjaxOptions { 
                                HttpMethod="POST", 
                                OnFailure="alert('fail');", 
                                OnSuccess = "alert('success');" 
                            })%>

I get a "not found" error when it tries to route this request.

If I remove the POST restriction from the UpdateComments method in the controller, it works fine.

What am I missing?

Blunder answered 14/6, 2010 at 11:44 Comment(0)
B
7

It seems it didn't like the way I was declaring my OnFailure and OnSuccess callbacks. I guess it couldn't parse my AjaxOptions object so was ignoring the HttpMethod="POST" setting.

I got it working by changing it to:

OnFailure="function() { alert('fail'); }",
OnSuccess="function() { alert('success'); }" 
Blunder answered 14/6, 2010 at 11:59 Comment(0)
H
4

I am learning ASP.MVC at this moment and I had that issue with my Ajax.ActionLink, I got a GET method and not a POST method as it should had been. Then I realize that I didn't add the scripts library reference:

<script src=”/Scripts/MicrosoftAjax.js” type=”text/javascript”></script>
<script src=”/Scripts/MicrosoftMvcAjax.js” type=”text/javascript”></script>

After I adding the script it worked fine!

Horology answered 29/4, 2011 at 18:53 Comment(1)
E
1

try including

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftMvcAjax.js")" type="text/javascript"></script>
Eucaine answered 10/1, 2012 at 0:46 Comment(2)
Welcome to Stack Overflow! Could you please elaborate on why this will help? A large part of a good answer is not only understanding the solution, but understanding why things were a problem to begin with!Perinephrium
These are obsolete in MVC3 and MVC4. See: https://mcmap.net/q/320543/-are-microsoftajax-js-microsoftmvcajax-js-and-microsoftmvcvalidation-js-obsolete-as-of-asp-net-mvc-3Northcliffe
P
0

FormCollection has a default binder associated with it which always initializes the collection and you should never get null. It is more likely that you have an empty collection when using Ajax.ActionLink in contrast to when using a form submit button. This is because the ActionLink method doesn't POST any form values when it performs the AJAX request. This post is the unswer to you question

Pharynx answered 20/1, 2011 at 14:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.