Kraishan
Kraishan

Reputation: 455

ASP.Net view folder with a folder inside - How to create the controller

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

Answers (2)

Win
Win

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 }
        );
    }
}

Controller

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();
    }
}

enter image description here

Upvotes: 4

Mathew Thompson
Mathew Thompson

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

Related Questions