2011-12-13 130 views
0

我剛開始使用MVC 3,並且想創建一個像'http:// server/news/9635/demo-news-title'這樣的url,但我不知道如何才能地圖路線。MVC 3 URL路由

routes.MapRoute(
       "news", 
       "{controller}/{id}/{title}", 
       new { controller = "news", action = "Index", id = UrlParameter.Optional, title = UrlParameter.Optional } 
       ); 

我試過了,但它似乎沒有工作。我該怎麼辦?

感謝

+0

什麼是 '不工作'?你是否得到例外?找到錯誤的控制器?你期望什麼具體沒有發生? – dougajmcdonald

+0

當我向瀏覽器寫入'/ news/221/demo-title'時,出現「服務器錯誤/應用程序」錯誤。 mapRoute方法適用於我上面寫的url嗎? – mehmetserif

+0

你能告訴我們你的控制器動作嗎? – frennky

回答

1

我認爲您的路線是正確的,但您必須在默認路線之前放置您的路線。這是例子:

routes.MapRoute(
       "news", 
       "{controller}/{id}/{title}", 
       new { controller = "news", action = "Index", id = UrlParameter.Optional, title = UrlParameter.Optional } 
       ); 
routes.MapRoute(
       "Default", // Route name 
       "{controller}/{action}/{id}", // URL with parameters 
       new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults 
      ); 
2

您沒有提供關於你的意思「不工作」的信息。 要檢查您的路線是否是您可以使用的問題Phil Haacks's ASP.NET Routing Debugger

+0

以及我的事情,我解決了這個問題,我得到了2個maproutes,一個默認和一個新聞,所以我改變了他們的順序,現在看來工作... – mehmetserif

0

這樣來做:

routes.MapRoute(
      "news", 
      "news/{id}/{title}", 
      new { controller = "news", action = "Index", id = UrlParameter.Optional, title = UrlParameter.Optional } 
      );