Derek Flenniken
Derek Flenniken

Reputation: 487

ASP.NET MVC Routing Root Level Views

I thought this would be fairly easy, but I'm totally baffled.

I want one controller's views to be at the root level of the application, rather than in a subdirectory for that controller, but I cannot figure it out.

I'd like to have these two urls:

/Info - This should action "Info" on controller "Home"

/Admin/ - This should be action "Index" (default) on controller "Admin"

So far no matter what I've tried, the first route will end up catching both. I can't seem to separate the two.

That Info page doesn't even need a controller, it' static, but I do want to use a master page. There may be a much easier way to pull this off, but I haven't figured that out either.

All I can think of that would work, would be to create an Info controller, and move Views/Home/Info to Views/Info/Index, but that has a certain smell to it.

I was able to do this in rails using:

  map.connect ':controller/:action/:id'
  map.connect ':action', :controller => 'home'

Upvotes: 6

Views: 5968

Answers (2)

guyfromfargo
guyfromfargo

Reputation: 863

You can use Route Attributes.

In your route config file you should have.

        routes.MapMvcAttributeRoutes();
        AreaRegistration.RegisterAllAreas();
        //code below should already be in your route config by default
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

Then above every action you can have a route attribute.

 [Route("info")]

You can even get more advanced with these attributes by adding parameters, and/or subfolders

 [Route("blog/posts/{postId}")]

You can put the above attribute on any action, and it will appear as if it's originating from the blog controller. However, you don't even need a blog controller. Also the {} signify the parameter, so just make sure your action is taking the same parameter as what's in the curly braces. In this case the parameter would be

string postId

Upvotes: 0

Arnis Lapsa
Arnis Lapsa

Reputation: 47597

You just need proper routes. In your case:

routes.MapRoute(
                "Info",
                "Info",
                new { controller = "Home", action = "Info" }

routes.MapRoute(
                "Admin",
                "Admin",
                new { controller = "Admin", action = "Index" }

But i recommend you this approach.

If you need to change default physical location of views/partialviews,
check out how to create custom view engines.

Upvotes: 6

Related Questions