I've been wrestling this error for quiet a while now and tried all the suggestions found on the web, still no luck.
I'm doing a simple ajax call to a controller's action. The application is in EPiServer, but this seems to be a generic question regarding using Ajax in ASP.NET.
Index View:
<input id="btnAjax" type="button" value="Favorite" />
<script>
$('#btnAjax').click(function () {
$.ajax({
url: '@Url.Action("SetCookie", "Home")',
contentType: 'application/html; charset=utf-8',
type: 'POST',
dataType: 'html'
})
.success(function (result) {
alert("Success");
})
.error(function (xhr, status) {
alert(status);
})
});
</script>
Controller - HomeController:
[HttpPost]
public void SetCookie()
{
//Do stuff
}
What I've done/tried:
Referenced jquery correctly.
Added the [WebMethod] attribute to the action
Added a Http module in Web.config (ScriptModule, for EPiServer)
Added Reference to jquery.unobtrusive-ajax.js, after the reference to jquery.
When I run the webapplication and push the button the debugger in Developer tool tells me
which is strange, since there is an action/method called SetCookie() in the HomeController. And the alert box "Fail" shows, which indicated that at least the js function is invoked.
Either I'm blind and missing something or there is something else which needs to be done...
All suggestions are welcome and much appreciated.
/ChrisRun
EPiServer does not register the default route for MVC by default. This is because you could have a page called "Home" in your site that would confict with the Home route. You can register the route yourself in Global.asax by overriding the RegisterRoutes method:
protected override void RegisterRoutes(RouteCollection routes)
{
base.RegisterRoutes(routes);
// Register a route for Web API
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "webapi/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Register a route for classic MVC to use for API calls
routes.MapRoute(
name: "API",
url: "api/{controller}/{action}/{id}",
defaults: new { action = "Index", id = UrlParameter.Optional });
}
I like to put MVC and Web API routes under a prefix such as "webapi" or "api" so that it's less likely to conflict with any content routing.