Joe Enos
Joe Enos

Reputation: 40431

ASP.NET MVC subdirectories

I'm still kind of new to MVC, so I'm hoping this is simple.

I need categories and subcategories, potentially multiple levels deep, and I'm trying to organize my project appropriately. Right now I'm using the out-of-the-box MVC project in VS2008.

For example, suppose I want to navigate to: http://mysite.com/Products/Electronics/Computers/Laptops

I can accomplish this by putting a LaptopsController in my Controllers directory, a Latops directory with the various aspx files in my Views, and adding a line to my Global.asax class that maps this specific route to the appropriate controller.

But I'm hoping there's a way to automatically map the route, while at the same time keeping the directory structure clean and organized in the project, since there will be a lot of different categories and products. Ideally there should be physical directories in my project for controllers and views, corresponding to the "directories" in the URL path. But I can't seem to make that work.

I've looked at a few articles about doing major customization to your routing, but I'd prefer not to if possible. This seems like it would be something built-in, so maybe I'm just missing something.

If you could point me in the right direction, that would be awesome.

Upvotes: 2

Views: 1745

Answers (2)

Nickz
Nickz

Reputation: 1880

IF your having trouble with routing try Haacked routing debugger.

http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx

If you want to catch all products info and get the content you can do the following:

    routes.MapRoute("Products", "products/{*params}", 
                    new { controller = "Product",  action = "Details", params= "" });


   public ActionResult Details(string params) 
   {     
           // Split the params with '/' as delimiter. 
           string [] productParams = params.Split('/');
           if(productParams.Lengh > 0)
           {
             var category = productParams.Length > 0 ? productParams[0]: null;
             var subCategory = productParams.Length > 1 ? productParams[1]: null;
             var detailModel //get model information and build return..

             ViewData.Model = detailModel; 
             Return View("Details");
           }
           Return View("Error");

          //etc.



   }

Upvotes: 0

Ethan Cabiac
Ethan Cabiac

Reputation: 4993

Most likely you don't need a LaptopsController, just a ProductsController. In this case, Electronics/Computers/Laptops just tells the ProductsController which category of Products to show (via route values).

Upvotes: 5

Related Questions