2012-10-07 81 views
2

我有一個索引操作的控制器。ASP.NET MVC 4路由查詢 - 將查詢字符串傳遞給索引操作

public ActionResult Index(int id = 0) 
{ 

    return view(); 
} 

我想ID傳遞到索引行動,但它不出現在相同的方式行動的細節工作。

例如如果我想ID 4通入索引的動作,我要拜訪網址:

http://localhost:8765/ControllerName/?id=4 

隨着細節動作......我能做到這一點。

http://localhost:8765/ControllerName/Details/4 

我想與指數做的是一樣的東西......

http://localhost:8765/ControllerName/4 

當我訪問這個URL,我得到一個錯誤:

Server Error in '/' Application. 

The resource cannot be found. 

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly. 

Requested URL: /fix/1 

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.17929 

這可能嗎?我怎樣才能讓MVC以與細節相同的方式自動處理索引操作?

感謝

更新 - 我現在的ROUTES CONFIG

public class RouteConfig 
{ 
    public static void RegisterRoutes(RouteCollection routes) 
    { 
     routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

     routes.MapRoute(
      name: "Default", 
      url: "{controller}/{action}/{id}", 
      defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
     ); 
    } 
} 

更新。新RouteConfig類仍然當我訪問本地主機不工作:1234 /修正/ 3

public class RouteConfig 
{ 
    public static void RegisterRoutes(RouteCollection routes) 
    { 
     routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

     routes.MapRoute(
      name: "Default", 
      url: "{controller}/{action}/{id}", 
      defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
     ); 

      routes.MapRoute(
      name: "FixIndexWithParam", 
      url: "Fix/{id}", 
      defaults: new { controller = "Fix", action = "Index", id = UrlParameter.Optional }); 
    } 
} 
+0

我們需要看到什麼在你的'RoutesConfig .cs'文件 – Mark

+0

使用我的RouteConfig更新的問題 – Gravy

+1

僅供參考:我編輯了您的問題以刪除對EntityFramework的引用,這個問題與EF無關,只是關於它。NET路由實現和它將這些請求映射到MVC控制器的方式 –

回答

5

更新值得指出的是,/ ControllerName/Index/4應該使用默認路由。

在那裏使用默認路由,它期望第二個參數是控制器名稱。

所以與默認路由/ ControllerName/4被interpereted爲ControllerNameController行動4,當然不存在。

如果默認的一個前加

routes.MapRoute(
name: "IndexWithParam", 
url: "{controller}/{id}", 
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }); 

它將允許

/主頁/ 4被路由到HomeController行動Indexid=4

我have't測試這一點,可能與默認設置衝突。您可能需要在路徑明確指定控制器,即:

routes.MapRoute(
name: "HomeIndexWithParam", 
url: "Home/{id}", 
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }); 

(顯然,更換Home與任何控制器,你實際上是想路線)

+1

謝謝,我創建了一個新的路由,但仍存在問題......查看更新的問題。 – Gravy

+0

對不起,我回復之前,我粘貼它。請檢查更新 – Gravy

+1

你需要添加新的路由之前的默認路由,他們按順序執行 –

相關問題