2016-11-24 129 views
1

我正在製作一個類似庫的網站。在這個圖書館裏,一篇文章可以有一個類別,而這個類別最多可以有兩個父類別,比如:「世界>國家>城市」。多參數MVC路由

我希望所有文章的名稱爲LibraryController的所有文章都保留對單個控制器的所有視圖顯示。和所使用的2個行動是Article(string id)Category(string[] ids)

要查看名爲「聖殿騎士團」的用戶必須輸入的文章:/library/article/the-templar-order

好了,所以現在的類別。我有我的頭2層的方法,這個例子是查看「城市」類別:

  1. 簡單的方法:/library/world-country-city
  2. 一個我想:/library/world/country/city
  3. 一個我不想,因爲它變得太笨拙了:/library/category/world/country/city

但是我對如何去創建一個需要3個參數並且基本上沒有任何操作的路由有點困惑。而除了第一個參數「世界」剩下的應該是可選的,就像這樣:"/library/world/">"/library/world/country/">"/library/world/country/city/"

那麼我將如何去建立這樣一個路線?

解決方案

RouteConfig.cs

// GET library/article/{string id} 
routes.MapRoute(
    name: "Articles", 
    url: "Library/Article/{id}", 
    defaults: new { controller = "Library", action = "Article", id = "" } 
    ); 

// GET library/ 
routes.MapRoute(
    name: "LibraryIndex", 
    url: "Library/", 
    defaults: new { controller = "Library", action = "Index" } 
    ); 

// GET library/category/category/category etc. 
routes.MapRoute(
    name: "Category", 
    url: "Library/{*categories}", 
    defaults: new { controller = "Library", action = "Category" } 
    ); 

回答

1

可以實現與以下兩個途徑。

// GET library/article/the-templar-order 
routes.MapRoute(
    name: "Articles", 
    url: "Library/Article/{id}", 
    defaults: new { controller = "Library", action = "Article" } 
); 

// GET library/world/country/city 
routes.MapRoute(
    name: "Category", 
    url: "Library/{*categories}", 
    defaults: new { controller = "Library", action = "Category" } 
); 

和輕微修改目標的行動

public ActionResult Category(string categories) { 
    categories = categories ?? string.Empty; 
    var ids = categories.Split(new []{'/'}, StringSplitOptions.RemoveEmptyEntries); 
    //...other code 
} 
+0

SRY我是接受的答案有點太快了。除了/圖書館/世界/國家/城市之外,我收到「找不到資源」。意味着像/ library/world這樣的URL會導致錯誤。 –

+0

顯示您映射路由的順序。訂單很重要,因爲第一場比賽獲勝。這可能意味着另一條路線在可以處理之前捕獲該網址。 – Nkosi

+0

感謝隊友,用最終的解決方案更新了問題......現在它完美地工作......這是確實導致問題的映射路線的排序...... –