Is it possible in MVC to do the following with a single controller "ListController" to take care of the following p开发者_StackOverflow中文版ages...
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.
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
}
Yes You can use multiple View in one Controller.
Let's take one Example, I have one Controller Called Lawyers
public class LawyersController : Controller
{
// GET: Lawyers
public ActionResult Login()
{
return View();
}
public ActionResult Signup()
{
return View();
}
so I have one controller and 2 views.
Routes could also be specified above methods with decorators so no need for RouteConfig. You just need to omit the "controller/" part from the route.
public ListController
{
// ... other stuff
[Route("Cars/ForSale/{id}")]
public ActionResult CarSale(int? id)
{
// do stuff
return View("CarView");
}
[Route("Boats/ForSale/{id}")]
public ActionResult BoatSale(int? id)
{
// do stuff
return View("BoatView");
}
// ... other stuff
}
精彩评论