开发者

MVC special routing

I have an asp.net MVC project where i need to define some custom routes. Similar to what you see for posts on Wordpress where the route is of the form postid-postname:

12-i-am-post

I know how to do something like postid/postname:

12/i-am-post.

But how do I make a route that combines the two, such as:

mywe开发者_开发问答bsite.com/12-postname-is-her


routes.MapRoute(
    "PostRoute", // Route name
    "{controller}/{id}-{postName}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional, postName = UrlParameter.Optional } // Parameter defaults
);


public ActionResult Index(int id, string postName)
{
    return View();
}

Should work for the following request http://localhost/Post/1-MyPostName


Since there are multiple hyphens you won't be able to use it as a delimiter/separator, unless you want it to always match the first occurrence. Your best bet is to do a catchall {*path} and parse the value in your controller.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜