CrazyLegs
CrazyLegs

Reputation: 618

How to route multiple parameters in MVC and C#

I have my default MVC routes setup as:

routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

What I want to be able to do is have the following routes in my Search controller hit.

.../Search/Uk
.../Search/Uk/County/Buckinghamshire
.../Search/Uk/City/London
.../Search/Uk/Town/Ashford
.../Search/Uk/Postcode/AB-Aberdeen

I only have one view called "Index". As I understood routing I presumed I should of been able to do something like this:

public ActionResult Index(string country)

public ActionResult Index(string country, string searchType, string location)

But no cigar, anyone understand what I'm doing wrong, do I need to add in some sort of routes configuration? Infact implementing this I cannot even load the search page

Upvotes: 0

Views: 2309

Answers (1)

Prasad Telkikar
Prasad Telkikar

Reputation: 16079

You can use attribute based routing where you can pass parameters in the route itself.

like,

//I hope you have already enabled attribute routing and search controller with RoutePrefix as "search"

[Route("{country}")]
public ActionResult Index(string country)
{
  //Your business logic
}

[Route("{country}/{searchType}/{location}")]
public ActionResult Index(string country, string searchType, string location)
{
  //Your business logic
}

Enabling Attribute based routing : MSND

Upvotes: 1

Related Questions