deshergan
deshergan

Reputation: 73

Attribute Routing with multiple optional parameter

I have a controller named "view" with below action that has multiple optional parameters. I want to use the Attribute Routing to generate URLs like these:

/view/keyword/sometext/country/canada
/view/country/canada
/view/keyword/sometext/country/canada/city/calgary
/view/keyword/sometext/country/canada/state/alberta
/view/country/canada/state/alberta/page/1

As you can see, there could be a various combination of URLs since all of these parameters are optional.

However, if i use like below, i get error if the requested url doesn't match or one of the optional Parameter is null.

[Route("view/keyword/{keyword}/country/{country}/state/{state}/city/{city}/page/{page}")]
public ActionResult Index(int? page, string keyword = "", string city = "", string state = "", string country = "")
{
    return view();
}

If i use like below, some of the url works but that would take me to write 20+ new routes depending on number of parameters. I am using MVC 5.

[Route("view/keyword/{keyword}/country/{country}/state/{state}/city/{city}/page/{page}")]
[Route("view/keyword/{keyword}/country/{country}/state/{state}/page/{page}")]
[Route("view/keyword/{keyword}/country/{country}/city/{city}/page/{page}")]
[Route("view/keyword/{keyword}/state/{state}/city/{city}/page/{page}")]
[Route("view/state/{state}/city/{city}/page/{page}")]
public ActionResult Index(int? page, string keyword = "", string city = "", string state = "", string country = "")
{
    return view();
}

Any suggestions please?

Upvotes: 0

Views: 2322

Answers (1)

WeShall.NET
WeShall.NET

Reputation: 99

May be you can add your routes in the RoutesConfig.cs file. In the RoutesCollection collection of the RegisterRoutes method. placing the default one (which is already present) at the last place.

routes.MapRoute(
        "CustomRouteName",           // Route name
        "view/state/{state}/city/{city}/page/{page}"// URL with parameters
        new { controller = "View", action = "Index", state = "", city = "", page="" }
    );

Upvotes: 1

Related Questions