ASP.NET MVC Routing with Default Controller

前端 未结 3 596
清酒与你
清酒与你 2020-12-08 08:10

For a scenario, I have a ASP.NET MVC application with URLs that look like the following:

http://example.com/Customer/List
http://example.com/Customer/List/Pa         


        
3条回答
  •  一整个雨季
    2020-12-08 08:59

    Why does the first URL in the new list still have "Customer". I assume that's a typo and you meant:

    • http://example.com/List
    • http://example.com/List/Page/2
    • http://example.com/List
    • http://example.com/View/8372
    • http://example.com/Search/foo/Page/5

    The following routes work for me:

    routes.MapRoute(
        "CustomerSearch"
        , "Search/{query}/Page/{page}"
        , new { controller = "Customer", action = "Search" }
    );
    
    routes.MapRoute(
        "CustomerGeneric"
        , "{action}/{id}/Page/{page}"
        , new { controller = "Customer" }
    );
    
    //-- Default Route
    routes.MapRoute(
        "Default",
        "{action}/{id}",
        new { controller = "Customer", action = "Index", id = "" }
    );
    

    How are you generating your links. Since the Controller is no longer in the URL of your route (aka, you don't have "{controller}" in the route URL), but it's a default value, you need to make sure to specify the controller when generating routes.

    Thus instead of

    Html.ActionLink("LinkText", "ActionName")
    

    do

    Html.ActionLink("LinkText", "ActionName", "Customer")
    

    Why? Suppose you had the following routes.

    routes.MapRoute(
        "Default",
        "foo/{action}",
        new { controller = "Cool" }
    );
    
    routes.MapRoute(
        "Default",
        "bar/{action}",
        new { controller = "Neat" }
    );
    

    Which route did you mean when you call this?

    <%= Html.ActionLink("LinkText", "ActionName") %>
    

    You can differentiate by specifying the controller and we'll pick the one that has a default value that matches the specified one.

提交回复
热议问题