2013-03-12 45 views
1

在我的索引頁,我使用生成URL以下Asp.net MVC 4網址資源無法找到

@foreach(var c in ViewBag.cities) 
{ 
    <li>@Html.ActionLink((string)c.CityName,"somepage",new{city=c.CityName, id=c.Id})</li> 
} 

將在以下格式

localhost:55055/1/city1 
localhost:55055/2/city2 
... 

其中1生成的URL爲每個城市,2是Id和city1,城2是CITYNAME

我已經配置爲

routes.MapRoute(
      name: "CityRoute", 
      url: "{id}/{city}", 
      defaults: new { controller = "Home", action = "somepage", id = UrlParameter.Optional, city = UrlParameter.Optional } 
      ); 
01的路線

在家庭控制器的somepage操作方法:

public string somepage(int id, string city) 
{ 
    return city + " " + id; 
} 

即使我想這

public string somepage() 
{ 
    return "Hello"; 
} 

,但它會導致Resource cannot be found

我試圖把斷點sompage這是從來沒有擊中。

任何suggesstions

更新

正如評論所指出的@KD下面我改變了路線秩序和上面擺放的所有規則提到的原則之上。我也改變了方法

public ActionResult somepage(int id=0, string city="") 
{ 
    return Content(city + " " + id); 
} 

現在改變了行爲和默認規則

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

不用於正常的索引頁。相反,由於方法somepage中的斷點被擊中,並且如果我在瀏覽器中放置了http://localhost:55055/2/cityname,該頁面確實顯示了id和城市名。但現在默認路由不用於申請家庭http://localhost:55055/

+1

請更新您的標題與您的具體問題.. – 2013-03-12 08:43:42

+0

請確保您添加正確的順序路線。您添加的路線應位於默認路線的頂部。 – 2013-03-12 08:45:30

+0

也試試這個動作方法public ActionResult somepage(string id,string city) – 2013-03-12 08:46:35

回答

4

新的模式路線和缺省路由的模式幾乎是相同的,因此它總是會產生衝突,以匹配路線..改變你的路線以下

routes.MapRoute(
      name: "CityRoute", 
      url: "CitySearch/{id}/{city}", 
      defaults: new { controller = "Home", action = "somepage", id = UrlParameter.Optional, city = UrlParameter.Optional } 
      ); 

即增加一些前綴爲您的圖案,使它能夠很容易識別..像「CitySearch的」 ,然後提起您的路由名稱,同時提供操作鏈接,它..

或者,如果你不想添加前綴它然後做下面的事情,它將像一個魅力工作..

爲您的CityRoute添加一個路由約束爲Id將檢查ID字段是否爲整數。對於正常的URLS它將返回false,因此你的默認路由將得到評估...試試這個...

routes.MapRoute(
      name: "CityRoute", 
      url: "{id}/{city}", 
      defaults: new { controller = "Home", action = "somepage", id = UrlParameter.Optional, city = UrlParameter.Optional }, 
      constraints: new {id = @"\d+"} 
      ); 

這是正則表達式約束條件..把這條路線放在頂部並檢查。

+0

+1是的我同意,因爲所有其他鏈接現在指向'somepage'。 ''\ d +「肯定是衝突 – ZedBee 2013-03-12 09:22:02

+0

它說無法識別的轉義序列 – ZedBee 2013-03-12 09:29:31

+0

嘗試@」\ d +「來轉義 – 2013-03-12 09:42:33

0

由於您沒有定義的動作也不會叫這樣的錯誤來了

試試這個,

public ActionResult somepage(int id, string city) 
    { 
     return Content(city + " " + id); 
    }