2012-02-17 50 views
13

我正在嘗試識別如何將/ News/5的路由映射到我的新聞控制器。如何將/ News/5的路由映射到我的新聞控制器

這是我NewsController:

public class NewsController : BaseController 
{ 
    // 
    // GET: /News 

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

} 

這是我的Global.asax.cs規則:

 routes.MapRoute(
      "News", // Route name 
      "{controller}/{action}/{id}", // URL with parameters 
      new { controller = "News", action = "Index", id = -1 } // Parameter defaults 
     ); 

我試着去/新聞/ 5,但是我收到一個未找到資源錯誤,但是當去/新聞/索引/ 5它的作品?

我剛纔試過{controller}/{id}但這只是產生了同樣的問題。

謝謝!

+2

當你試圖'{控制器}/{id}'你是否保留默認操作? '新{控制器=「新聞」,行動=「索引」,編號= -1}' – Lazarus 2012-02-17 16:38:26

回答

18

{controller}/{id}您的{controller}/{id}路線是正確的,但您在另一條路線後註冊了它。在路線列表中,它從上到下搜索並找到第一個匹配的勝利。

爲了幫助引導路由,我建議爲此創建路由約束,以確保#1控制器存在,#2 {id}是一個數字。

this article

主要是:

routes.MapRoute( 
     "Index Action", // Route name 
     "{controller}/{id}", // URL with parameters EDIT: forgot starting " 
     new { controller = "News", action = "Index" }, 
     new {id= @"\d+" } 
    ); 
+0

非常感謝,我不能接受你的消息8分鐘,但我會回來。你用下面的約束來解決我的問題:'new {controller =「News」,id = @「0 | - ?[1-9] \ d *」} //路由限制,並將它移動到其他地圖路線上方 – ElveMagicMike 2012-02-17 16:40:46

6

你需要確保你的新的路線是你默認路由之前,像這樣:

routes.MapRoute(
     "NewsAbbr", // Route name 
     "{controller}/{id}", // URL with parameters 
     new { controller = "News", action = "Index", id = -1 } // Parameter defaults 
    ); 


    routes.MapRoute(
     "News", // Route name 
     "{controller}/{action}/{id}", // URL with parameters 
     new { controller = "News", action = "Index", id = -1 } // Parameter defaults 
    );