Using Url.RouteUrl() with Route Names in an Area

房东的猫 提交于 2019-11-29 13:09:51

Everyone please see @ryanulit's answer below. This issue may be fixed for you with a newer framework version.

Not sure if there has been a hot fix, but the behavior now is a bit different. Using your exact code and trying:

Url.RouteUrl("UserHome", new { id = 5 })

I now get:

/User/5?httproute=True 

This still looks awkward, so I experimented with the route and added another default param:

 context.MapRoute(
            "UserHome",
            "User/{id}",
            new { action = "Index", controller = "Home", area = "User", id = 0, 
                       httproute = true },
            new { controller = @"Home", id = @"\d+" }
        );

Now when I use

Url.RouteUrl("UserHome", new { id = 5 })

I get a nice url of

/User/5

disclaimer There could be unwanted side effects of httproute=true in the route declaration.

Also, the more verbose use:

@Url.RouteUrl("UserHome", new { controller = "Home", action = "Index", id = 5 })

still works as well.

Robson Douglas

Try this:

@Url.Action("Index", "Home", new { Area = "User" })

I can confirm that with .NET 4.5.1 and MVC 5.2.2 at the minimum, that this behavior has been fixed and now works as is with this same exact code using Url.RouteUrl("UserHome", new { id = 5 }).

It looks like this was a bug that has been fixed since the time of my post.

Adding this as the answer since although TSmith's solution would work, you no longer need to do that extra work now that there is a fix.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!