views:

21

answers:

2

I'm trying to handle the following url's: (1) domain.com, (2) domain.com/?latest

This is what I think should be it...

Global.asax

routes.MapRoute(
    "HomeIndex", // Route name
    "/?{sortBy}", // URL with parameters
    new { controller = "Home", action = "Index", sortBy = UrlParemeter.Optional } // Parameter defaults
);

HomeController.cs

public ActionResult Index(string sortBy) {
    if (string.IsNullOrEmpty(sortBy))
        // display stuff in a way that's sorted
    else
        // just display stuff by default
    return View( ... );
}

Issue: mvc doesn't like the route starting with hard-coded "?", but!, if don't map a route at all and just look for request.querystring["latest"], it comes up as null.

What's the best way to accomplish this? Thanks!

------- Edit:

I know that I shouldn't use just /?latest and I should instead use /?sortBy=latest , but, it's a shorter url!!!1 and easier to type :) I see that Google uses it sometimes, and I want to be like Google ;)

Setting aside the fact that it's not the best way to do it, is there a way to do /?latest ? Thanks!

+2  A: 

Your query string is incomplete. Try this: domain.com/?sortBy=latest. You can remove the extra route mapping as well and use the default routing.

Jeroen
A: 

You don't really need sortBy in your route definition. Just make sure the action method has an argument with the same name.

routes.MapRoute(
    "HomeIndex", // Route name
    "", // URL with parameters
    new { controller = "Home", action = "Index" } // Parameter defaults
);

And yes, in your route the part ?latest is not okay. It should always be in the form ?varname=varvalue.

Developer Art
but I see google doing that! it's easier to type :) I'm trying to avoid doing the ?key=value , to keep the url shorter. is it possible tho?? thanks!
Ian Davis
Then you might try checking whether the query string contains 'latest': Request.QueryString.Contains("latest") (or starts with).
Jeroen