Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP 404 with Ajax.ActionLink

I've trouble solving a 404 error:

Default Route in Global.asax.cs:

routes.MapRoute(
       "Default", 
       "{controller}/{action}/{id}",
       new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

VideoController.cs:

[HttpPost]
public ActionResult Save(int id)
{
   try
   {
     return Json(new
     {
       ID = "0"
     });
   }
   catch
   {
     return new HttpStatusCodeResult(418, "I'm a teapot");
   }
}

ActionLink in my view, Create.cshtml:

@Ajax.ActionLink("GoSave", "Save", "Video", new { id = 1 },
        new AjaxOptions { OnFailure = "Error", OnSuccess = "Saved", 
                          HttpMethod = "POST" })

The url of the actionlink is rendered as expected: /Video/Save/1

When I click on the link I get an 404.

What is it I'm not seeing?

like image 666
Andrew Avatar asked Mar 25 '11 19:03

Andrew


2 Answers

I bet you are missing a script inclusion:

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

This will unobtrusively AJAXify the Ajax.ActionLink generated result and perform a POST request instead of the default GET one. You are getting 404 because you haven't included this script and so a GET request is sent and there is no Save action on Video controller capable of receiving a GET request.

If you have used FireBug you would immediately have seen this: that the browser is simply redirecting and sending a GET request instead of the expected Ajax POST request.

like image 130
Darin Dimitrov Avatar answered Sep 30 '22 19:09

Darin Dimitrov


Adding to Darin's answer...

Add this NuGet package, which "unobtrusively sets up jQuery Ajax."

enter image description here

All this package does is install the necessary scripts.

enter image description here

Next, do what Darin says or, equivalently, add:

@Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js") 

to _Layout.cshtml

like image 40
brntsllvn Avatar answered Sep 30 '22 18:09

brntsllvn