2016-06-14 275 views
0

我在ASP.net MVC是新Asp.net MVC 5路由

我的路由配置是這裏

routes.MapRoute(
      name: "ItineraryRoute", 
      url: "{country}/Itinerary/tours/{TourId}", 
      defaults: new { controller = "TourDetails", action = "Index" } 
    ); 

     routes.MapRoute(
      name: "TourRoute", 
      url: "{country}/tours", 
      defaults: new { controller = "Tour", action = "Index" } 
     ); 

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

/Russia/tours頁我這裏有一個環節是代碼行:

<a href="@ViewBag.Country/tours/Itinerary/@tour.Id">Day's By Detail's....</a> 

當我點擊這個,頁面會鏈接到這個網址:/Russia/Russia/tours/Itinerary/1

因錯誤404未找到http。

你有什麼想法,爲什麼我有兩個俄羅斯,如何解決它與'TourId'的'TourDetailsController'鏈接?

+3

Perpend一個'/'。但是你應該總是使用'@ Url.Action()'或'@ Html.ActionLink()'來產生正確的URL。 –

+0

是否可以回答這個問題,並告訴我在這種情況下如何使用'@ Html.ActionLink()'? –

+0

我不知道該如何謝謝你。謝謝 。 –

回答

4

您需要perpend一個/(正斜槓)到href值 - 即,使得其href="/Russia/tours/Itinerary/1",但你應該總是使用UrlHelperHtmlHelper方法來生成你的鏈接

使用Url.Action()

<a href="@Url.Action("Index", "TourDetails", new { country = ViewBag.Country, tourID = tour.Id })">Day's By Detail's....</a> 

使用Url.RouteUrl()

<a href="@Url.RouteUrl("ItineraryRoute", new { country = ViewBag.Country, tourID = tour.Id })">Day's By Detail's....</a> 

使用Html.Action()

@Html.ActionLink("Day's By Detail's....", "Index", "TourDetails", new { country = ViewBag.Country, tourID = tour.Id }, null) 

使用Html.RouteLink()

@Html.RouteLink("Day's By Detail's....", "ItineraryRoute", new { country = ViewBag.Country, tourID = tour.Id }) 
+0

是的它的工作原理,真的非常感謝您的幫助和知識。 –

+1

只需注意有關「/ xxx」的路徑 - 網站的根目錄可能並不總是位於網絡服務器的根目錄(尤其是使用IIS應用程序)。這就是爲什麼MVC Razor瀏覽器使用「〜/ images ...」等等。如果你將路徑硬編碼爲「/ xxx」,並且你的網站被移動/部署到「/ mysite」,那麼它應該是「/ mysite/xxx」和硬編碼路徑將停止工作。助手(詳見此處)爲您處理。總是使用助手。 –