简体   繁体   中英

Url.Action() does not remove default values

I have rather a simple routing map.

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

Now, If use Url.Action("Index", "Home") , it does not properly remove defaults values of the route. And it gives me /Home/Index .

Now, if I remove either {id} or {seoName} , and its corresponding default value, then the URL is properly generated like / (root).

What I am missing here? It does not seem to be an ambient value, since I am visiting the main page with no ids, nor seoNames.

Any ideas?

You would need multiple mappings to achieve what you want as you are only allowed to make the last route placeholder optional.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM