J4N
J4N

Reputation: 20761

ASP.Net MVC3: Create custom URL without having the exact controller name in it

For a project I've to(unfortunately) match some exact url.

So I thought it will not be a problem, I can use the "MapRoute", to match urls with the desired controller. But I can't make it work.

I've to map this URL:

http://{Host}/opc/public-documents/index.html

to

Area: opc
Controller: Documents
Action: Index

Another example is to map

http://{Host}/opc/public-documents/{year}/index.html

to

Area: opc
Controller: Documents
Action:DisplayByYear
Year(Parameter): {year}

I tried this, whitout success, in my area(ocpAreaRegistration.cs):

context.MapRoute("DocumentsIndex", "opc/public-documents/index.html", 
    new {area="opc", controller = "Documents", action = "Index"});
context.MapRoute("DocumentsDisplayByYear", "opc/public-documents/{year}/index.html", 
    new {area="opc", controller = "Documents", action = "Action:DisplayByYear"});

But I got some 404 Errors :( when I'm trying to access it. What am I doing wrong?

Upvotes: 2

Views: 626

Answers (1)

John H
John H

Reputation: 14640

I'm not sure why you need to do this (I can only assume you're coming from a legacy application), but this is working for me:

opcAreaRegistration.cs:

public override void RegisterArea(AreaRegistrationContext context)
{
    context.MapRoute(
        "opc_public_year_docs",
        "opc/public-documents/{year}/index.html",
        new { controller = "Documents", action = "DisplayByYear" }
    );

    context.MapRoute(
        "opc_public_docs",
        "opc/public-documents/index.html",
        new { controller = "Documents", action = "Index" }
    );

    context.MapRoute(
        "opc_default",
        "opc/{controller}/{action}/{id}",
        new { action = "Index", id = UrlParameter.Optional }
    );
}

Controller:

public class DocumentsController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult DisplayByYear(int year)
    {
        return View(year);
    }
}

Make sure you put those routes in the area routing file rather than global.asax and you should be good to go.

Upvotes: 2

Related Questions