2010-07-15 24 views
1

可以說我有一個名爲Store的控制器。有一個索引方法:C#,ASP.NET MVC/MVC2:爲特定控制器添加通配符路由 - 幫助構建路由

public ActionResult Index(string val, long? id, int? id2) 
{ 
    return View(); 
} 

我要取的東西,如:

/my-store/some-text 
/my-store/some-text/ 
/my-store/some-text/123456789
/my-store/some-other-text/4562343462345 
/my-store/some-other-bla-text/4562343462345/1 
/my-store/some-other-bla-bla-text/45345723554/2 

所以requerements是:
+控制器鏈接文本是「我的店」,具有路由到存儲控制器
+如果只有一些文字和編號,然後見好就收ID2空
+如果只有一些文字和沒有id,然後就離開ID和ID2空

以下是否正確?

routes.MapRoute(
    "Store", // Route name 
    "my-store/{val}/{id}/{id2}", // URL with parameters 
    new { controller = "Store", action = "Index", id = UrlParameter.Optional, id2 = UrlParameter.Optional } 
); 

謝謝您的幫助!

回答

1

呀看起來不錯,除非你需要在你的路線定義爲{VAL}默認值:

routes.MapRoute(
"Store", // Route name 
"my-store/{val}/{id}/{id2}", // URL with parameters 
new { controller = "Store", action = "Index", val = "", id = UrlParameter.Optional, id2 = UrlParameter.Optional } 

只記得清理字符串val中,如果你有一些時髦的字符,那麼你的鏈接贏得了」工作。就像我們說VAL等於「THISIS/VAL」,那麼你的鏈接將是:

/我店/ THISIS/VAL/1212年至1212年

這不會打你的路線,最有可能返回404