ASP.NET MVC - Mapping more than one query string parameter to a pretty url

11,628

Solution 1

Assuming that the allowed values for location and order are unique (i.e. when they come in, you can tell them apart, or else if they only supply one, how are you going to know if it's a location or an order?), then you could just take two parameters and work out what they are in the controller.

Route: {controller}/{action}/{param1}/{param2}

Controller action:

public ActionResult MyAction(string param1, string param2)
{
    string location;
    string order;
    if (!ParseLocation(param1, out location))
    { ParseLocation(param2, out location); }
    // ...
}

Not particularly elegant, but does let you have the URLs you want.

Solution 2

Click on your profile link and look at the URLs for Stats, Recent, Response, etc.

Examples:

with no sort it defaults to stats

Optional paramters should be query parameters

Solution 3

You will always have this issue if you have multiple optional parameters. Either make one or both of them non-optional (and positioned earlier in the query string than the optional one) or use the querystring parameter notation.

Share:
11,628
Admin
Author by

Admin

Updated on June 11, 2022

Comments

  • Admin
    Admin almost 2 years

    I am a bit stuck on the design of my seo friendly urls for mvc....Take for example the following url: http://myapp/venues/resturants.aspx?location=central&orderBy=top-rated

    With my mvc app i have mapped it as follows: http://myapp/venues/list/resturants/central/top-rated
    {controller}/{action}/{category}/{location}/{order}

    Now the only problem is that location and order are optional...so it should be possible to submit a request like: http://myapp/venues/list/resturants/top-rated . This proves to be a problem when the request hits the controller action, the location parameter has picked up "top-rated", naturally.

    Any suggestions? I' am considering using explicit querystrings to handle more than one parameter but this is really my last option as i dont want to sacrifice SEO too much.

    Has anyone eles run into such dilemmas? And how did you handle it?

    Thanks in advance!

  • Admin
    Admin over 15 years
    yep, was exploring this method. I guess i was kinda hoping someone has done something clever with the RouteBase class or something special with the routetables....Thanks alot!