簡體   English   中英

無法找到Asp.net MVC 4 Url Resource

[英]Asp.net MVC 4 Url Resource cannot be found

在我的索引頁面中,我使用以下內容生成URL

@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,2是Id和city1,city2是CityName

我已將路線配置為

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

Home Controller中的somepage動作方法:

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

即使我試過這個

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

但它導致Resource cannot be found

我嘗試將斷點放在從未被擊中的sompage中。

任何建議

更新

正如@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和cityname。 但現在默認路由不用於應用程序主頁http://localhost:55055/

您的新路線和默認路線模式的模式幾乎相同,因此它將始終產生沖突以匹配這些路線。將您的路線更改為以下

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

即為您的模式添加一些前綴,以便它可以輕松識別..像“CitySearch”,然后提供您的路線名稱,同時為它提供行動鏈接..

或者,如果您不想為它添加前綴,那么請執行以下操作,它將像魅力一樣工作。

對於您的CityRoute,為Id添加一個Route Constraint,它將檢查ID字段是否為Integer。 對於普通的URL,它將返回false,因此您的默認路由將被評估...試試這個......

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

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

由於您尚未定義Action,因此不會調用它,因此會出現錯誤

嘗試這個,

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM