Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActionLink 404 Error

Building my first ASP.NET MVC 3 application and trying to implement the ability to disassociate a given ice cream from a menu. Each has an integer identifier associated with it and on a page I display these mappings and provide a link by them to remove the ice cream from the menu.

I've got an ActionLink that looks like this:

@Html.ActionLink("Remove", "RemoveMenuIceCreamMapping", "IceCream", new { iceCreamId=item.IceCreamId, menuId=item.MenuId}, null)

In my IceCreamController I've got an Action that looks like this:

[HttpPost]
public PartialViewResult RemoveMenuIceCreamMapping(int iceCreamId, int menuId)
{
   ...
}

Did a little searching and believe I may need to modify the routes in the Global.asax.cs file's RegisterRoutes to handle these two parameters. So I tried this like so:

public static void RegisterRoutes(RoutesCollection routes)
{
   routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

   // I added this route in an attempt to handle the two parameters:
   routes.MapRoute(
      "RemoveMenuIceCreamMapping", // Route name
      "IceCream/RemoveMenuIceCreamMapping/{iceCreamId}/{menuId}", // URLwith parameters
      new
      {
         controller = "IceCream",
         action = "RemoveMenuIceCreamMapping",
         iceCreamId = UrlParameter.Optional,
         menuId = UrlParameter.Optional
      } 
   );

   // this was there by default
   routes.MapRoute(
      "Default",
      "{controller}/{action}/{id}",
      new {controller = "Home", action = "Index", id = UrlParameter.Optional }
   };
}

But this doesn't work - I get a "The resource cannot be found." error, 404. Requested URL: /IceCream/RemoveMenuIceCreamMapping/1/10

1 is the Id of the IceCream and 10 is the menu's Id.

What I was expecting to happen was that the action RemoveMenuIceCreamMapping would get called, passing those two parameters, but I'm obviously not doing something right here and may just misunderstand how to accomplish what I want and be going about this the wrong way. Any guidance would be most appreciated.


Update

So, one more thing I've learned, after reading this SO question, my ActionLink isn't triggering a POST so removing the [HttpPost] from the action seemed like the right thing to do. And, in fact, as soon as I did that, the route was found and the action executed.

like image 212
itsmatt Avatar asked Aug 22 '11 15:08

itsmatt


1 Answers

I think you problem is that the ActionLink uses an HTTP GET and you are only accepting HTTP POST.

You will probably need to change your view to issue an HTTP POST (e.g. with a regular HTML button inside a form) so that the verb that the browser sends matches with what you accept on the controller.

like image 159
Hector Correa Avatar answered Oct 24 '22 00:10

Hector Correa