开发者

How to add route for and handle domain.com/?latest

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 requ开发者_开发技巧est.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!


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜