Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax.ActionLink POST doesn't work in ASP.NET MVC 5

A quick summary of the situation:

In my View I have this piece of Razor code:

@{
ViewBag.Title = "Index";

AjaxOptions options = new AjaxOptions();
options.HttpMethod = "POST";
}

...

@Ajax.ActionLink("Linkname", "CreateChallenge", new { challengedId = Model.UserId },options);

Than in my controller:

[Authorize]
[HttpPost]
    public string CreateChallenge(string challengedId)
    {
        ChallengeRepository.CreateChallenge(challengedId);
        return "Sendend!";
    }

I get an 'Resource not found' error when I click the link but when I remove the [HttpPost] attribute everything works fine. But I want a POST method. I have looked around and found some similar problems but none of the solutions worked for me.

like image 971
Jenthe Avatar asked Jan 08 '14 10:01

Jenthe


1 Answers

UPDATE Spoke too soon, remembered that you need the jQuery.Ajax.Unobtrusive http://www.nuget.org/packages/jQuery.Ajax.Unobtrusive/ package

If you install this and reference it in you view it should work, it did i my OOTB test :)

Did a quick test myself, it seems you cant use Ajax.ActionLink to issue a POST request, it does a GET even though you set POST in AjaxOptions. You can see this if you use fiddlr to monitor the traffic.

You can also use the Postman extension for Chrome to test it, you will see that the action method actually behaves as it should when you POST to it. But you get the 404 because it actually does a GET

If it were me I would use jQuery to do the post. You can see more here http://api.jquery.com/jquery.ajax/

like image 57
Christian Sparre Avatar answered Sep 22 '22 07:09

Christian Sparre