Flezcano
Flezcano

Reputation: 1687

Asp.net Mvc Route not working

I have the following route on my mvc 5 project. When I try to access to the action by url, it throws an 404 error page. What am I doing wrong?

RouteConfig.cs

  .... 
routes.MapRoute
       (
              name: "EventMoneyMovements2",
              url: "eventos/{eventID}/movimientos",
              defaults: new { controller = "EventMoneyMovements", action = "ListByEvent", eventID = UrlParameter.Optional }

       );

Controller

public class EventMoneyMovementsController : Controller
    {
        //
        // GET: /EventMoneyMovements/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult ListByEvent(int? eventID)
        {

            return View();
        }

    }

Upvotes: 0

Views: 1428

Answers (2)

Saurabh Saxena
Saurabh Saxena

Reputation: 117

You must define your custom route before default MVC route because all routes defined in route config maintained in a route table in same order as we define in route config.

For more information refer below url:

http://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/creating-custom-routes-cs

Upvotes: 1

Shyju
Shyju

Reputation: 218702

The order in which you are registering the routes matters. You should always register your specific routes before the generic default route.

Assuming you register your specific route before your generic like below.

public static void RegisterRoutes(RouteCollection routes)
{
   routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
   routes.MapRoute
   (
          name: "EventMoneyMovements2",
          url: "eventos/{eventID}/movimientos",
          defaults: new { controller = "EventMoneyMovements", action = "ListByEvent",
                                                         eventID = UrlParameter.Optional }

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

With this definition you can access the ListByEvent action method with the request url

yourSiteName/eventos/101/movimientos or yourSitename/EventMoneyMovements/ListByEvent?eventID=101 where 101 is any int value

Upvotes: 1

Related Questions