Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC multiple views for a single controller

Tags:

asp.net-mvc

Is it possible in MVC to do the following with a single controller "ListController" to take care of the following pages...

www.example.com/List/Cars/ForSale/{id} optional

www.example.com/List/Cars/ForRent/{id} optional

www.example.com/List/Search/

www.example.com/List/Boats/ForSale/{id} optional

www.example.com/List/Boats/ForRent/{id} optional

www.example.com/List/Boats/Search/

If not, is there any way to get around it besides making a CarsController and BoatsController separate? They will be using the same logic just would like the URLs different.

like image 205
zach attack Avatar asked Feb 01 '11 18:02

zach attack


1 Answers

You can definitely do this. It is simple using routing. You can route the different urls to different actions in your controller.

Here are examples of defining some of the above urls:

routes.MapRoute("CarSale"
    "/List/Cars/ForSale/{id}",
    new { controller = "list", action = "carsale", id =  UrlParameter.Optional } );

routes.MapRoute("ListSearch"
    "/List/search",
    new { controller = "list", action = "search"} );


routes.MapRoute("BoatSale"
    "/List/Boats/ForSale/{id}",
    new { controller = "list", action = "boatsale", id =  UrlParameter.Optional } );

Then in your controller you would have action methods for each:

public ListController 
{
    // ... other stuff 

    public ActionResult CarSale(int? id)
    {
      // do stuff

      return View("CarView");
    }

    public ActionResult BoatSale(int? id)
    {
      // do stuff

      return View("BoatView");
    }

        // ... other stuff 
}
like image 120
Matthew Manela Avatar answered Jan 02 '23 23:01

Matthew Manela