Reputation: 455
I want to create a URL similar to: localhost:port/farm/animals/cow.cshtml. How do I create a controller for pages behind /animals/ ?
If I create a standard:
public class FarmController : Controller
{
//
// GET: /Farm/
public ActionResult Cow()
{
return View();
}
}
I will not get there because the cow.cshtml is behind the animals. Nor will I get to cow.cshtml with the following code:
public class AnimalsController : Controller
{
//
// GET: /Animals/
public ActionResult Cow()
{
return View();
}
}
Because the link to cow.cshtml is not /animals/ but /farm/animals/cow.
How can I solve this issue?
Upvotes: 3
Views: 4340
Reputation: 62290
You need to register a route like the following -
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Animals",
url: "farm/animals/{action}",
defaults: new { controller = "Farm" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
public class FarmController : Controller
{
// GET: Farm
public ActionResult Index()
{
return View();
}
// GET: Farm/Animals
public ActionResult Animals()
{
return View();
}
// GET: Farm/Animals/Cow
public ActionResult Cow()
{
return View();
}
}
Upvotes: 4
Reputation: 56429
Whilst routing would solve your problem, this sounds like a job for MVC areas. If in your actual application you're wanting to separate parts of your site, then an area might be the solution here.
Upvotes: 1