0

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?

1 Answer 1

1

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="" }
    );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.