2016-08-31 25 views
1

在我的MVC網站中,我想讓我的路線設置如下:無法路由到「{controller}/{action}/{id}」和「{controller}/{id}」

  • site.com/Customer - 您可以在這裏選擇一個客戶。

  • site.com/Customer/123 - 您可以在其中看到所選客戶的信息。

所以基本上,只有一個視圖,如果你有一個{id}顯示不同的東西。

所以我添加映射路徑DefaultNoActionRouteConfig.cs

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

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

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

並在控制器中執行以下:

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

和視圖:

@model int? 

... 

$(function() { 
    var customerId = @Model; 
    ... 
} 

現在:

  • ,如果我嘗試訪問site.com/Customer/123我會得到一個404
  • 如果我去site.com/Customer@Model沒有設置任何東西,所以當我引用它在我的jQuery它拋出一個語法錯誤,因爲它會看到var customerId = ;

很明顯,我沒有接近這個正確的方式或有更好的方式來做我想做的事情。任何方向?

+1

只是一個快速檢查 - 您是否刪除了「{controller}/{action}/{id}'的默認路由? – Max

+1

是默認路由之前的路由(該命令很重要) –

+0

請求將完整的RouteConfig.cs放在此處可以嗎?你一定可以去屬性路由。 –

回答

3

你的路由的順序物質(路由引擎將停止搜索時,找到的第一個匹配)。 ../Customer/123與您相匹配Default路由(它包含2段),並且您獲得404,因爲CustomerController中沒有名爲123的方法。您需要在Default路線之前移動DefaultNoAction路線。

但是這可能會導致其他問題與你的路由,你應該讓DefaultNoAction路線獨特,如果你也想使用Default路線

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

對於JavaScript錯誤,假設你要的customerId值要null如果方法id參數null,那麼你可以使用

var customerId = @Html.Raw(Json..Encode(Model)); 
console.log(customerId); // returns null if the model is null 

作爲一個側面說明,你的Parameters2路線也無法正常工作。只有最後一個參數可以標記爲Url.Optional,如果只提供一個或兩個參數,它將與Default路線相匹配。

2

使用屬性的路由在路由配置它

[Route("api/Customer/{id:int?}")] 
public ActionResult Index(int? id) 
{ 
    if (id!=null)  
     return View(id); 
    return View(); 
} 
+0

@apomene感謝您的幫助編輯 – Mostafiz

+2

'有用'編輯根本沒用 - 它與原始'return View(id);'代碼 –

+0

@StephenMuecke是一樣的但是OP的問題是路線,所以如果他解決了這個問題,那麼他可以實施其他邏輯 – Mostafiz

1

更改順序。第二個配置應該是第一個。我不檢查,但我認爲框架解釋url site.com/Customer/123Customer是控制器和123是行動的名稱。

視圖應該是這樣的:

@model int? 

... 

$(function() { 
    var customerId = @(Model ?? 0); 
    ... 
}