HTTP 404 with Ajax.ActionLink

南笙酒味 提交于 2019-12-07 04:41:04

问题


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?


回答1:


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.




回答2:


Adding to Darin's answer...

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

All this package does is install the necessary scripts.

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

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

to _Layout.cshtml



来源:https://stackoverflow.com/questions/5437136/http-404-with-ajax-actionlink

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!