Search code examples
asp.net-mvc-4asp.net-mvc-routingurl-routing

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


As a side note, I understand the whole ambiguous controller names problem and have used namespacing to get my routes working, so I don't think that is an issue here.

So far I have my project level controllers and then a User Area with the following registration:

public class UserAreaRegistration : AreaRegistration
{
    public override string AreaName
    {
        get
        {
            return "User";
        }
    }

    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "UserHome",
            "User/{id}",
            new { action = "Index", controller = "Home", id = 0 },
            new { controller = @"Home", id = @"\d+" }
        );

        context.MapRoute(
            "UserDefault",
            "User/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional }
        );
    }
}

The "UserHome" route is there so I can allow the route /User/5 vs. /User/Home/Index/5 which looks cleaner IMO.

Ideally I would like to use Url.RouteUrl("UserHome", new { id = 5 }), to generate the route elsewhere, but this always either comes back blank or gives me an exception saying it cannot find the route name, which is obviously there.

However when I use Url.RouteUrl("UserHome", new { controller = "Home", action = "Index", id = 5 }) it works no problem.

Why do I have to specify the action and controller when they have defaults already in the route mapping? What am I missing?


Solution

  • 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.