Wrong MVC route matched. Asp.net

2019-09-08 15:23发布

问题:

This is my route registration code:

        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "course_list",
            "course/list",
            new { controller = "course", action = "list" }
        );

        routes.MapRoute(
            "course_view",
            "course/view/{id}",
            new { controller = "course", action = "list", id = UrlParameter.Optional }
        );

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

I have a link /course/view/87

And the route that is matched is /course/list

Can anyone explain why?

Thank you

UPDATE:

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "course_list",
            "course/list",
            new { controller = "course", action = "list" }
        );

        routes.MapRoute(
            "course_view",
            "course/view/{id}",
            new { controller = "course", action = "view", id = UrlParameter.Optional }
        );

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

But I'm still getting the same issue. When i visit: /course/view/87 i get a 404 error.

回答1:

It appears that your route for course/view/{Id} has a 'list' action. I expect this is a typo.



回答2:

Adding these routes to an empty Asp.Net Mvc 4 project and using routedebugger (http://nuget.org/packages/routedebugger/), I get a Matched Route of "course/view/{id}". You should use routedebugger locally to see what is going on. The above code seems to be fine.



回答3:

The button element is treated as submit button (i.e.: type="submit" if not default type attribute is set). Therefore, the browser initiated a post request, which no route satisfied, since all my actions are get(s).

Thank you all for your time.