开发者

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开发者_如何学JAVA 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?


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.


Adding to Darin's answer...

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

HTTP 404 with Ajax.ActionLink

All this package does is install the necessary scripts.

HTTP 404 with Ajax.ActionLink

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

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

to _Layout.cshtml

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜