2011-03-01 44 views
3

正如標題狀態,我想我的MVC網站有一個URL格式,如:如何製作適用於我所有控制器的路線「{controller}/{action}/paramname/paramvalue/...」?

/Products/Category/Books/Sku/123456 

當所有其他URL段的參數名稱和值/名/值。

我該怎麼做?

+0

大小寫敏感或大小寫不敏感的? – 2011-03-01 16:28:01

+0

@Radek S-請勿區分大小寫 – 2011-03-01 16:31:50

+0

global.asax中只有一條路由嗎? – swapneel 2011-03-09 11:03:59

回答

10

ASP.NET路由允許在路線掩模的端部,以限定全部接收參數:

routes.MapRoute(
    "CategoryWithParameters", 
    "Products/Category/{category}/{*parameters}", 
    new { controller = "Home", action = "Index" } 
); 

所以這個主頁控制器方法

public ActionResult Index(string category, string parameters) 
{ 
    // slashes were ignored by routing system 
    string[] parts = parameters.Split('/'); 

    Dictionary<string, string> values = new Dictionary<string, string>(); 

    // we want only keys with values 
    for (int i = 0; i < parts.Length/2 * 2; i += 2) 
     values[parts[i]] = parts[i + 1]; 

    ViewBag.category = category; 
    ViewBag.parameters = parameters; 
    ViewBag.values = values; 

    return View(); 
} 

和該視圖

<p> 
@ObjectInfo.Print(ViewBag.category) 
</p> 
<p> 
@ObjectInfo.Print(ViewBag.parameters) 
</p> 
<p> 
@ObjectInfo.Print(ViewBag.values) 
</p> 

呈現URL h ** p:// localhost:32690/Products/Category/Bo OKS/SKU/123456 /兄弟/ 098765/DF/34〜

rendered view

相關問題