2009-09-22 71 views
0

考慮使用如此Nov. 2008 Phil Haack blog post中所述的區域約定的ASP.NET MVC 1.0項目。這個解決方案一旦建立就很好用!ASP.NET MVC:一個參數未命名爲ID和非整數的操作方法

由於我對ASP.NET MVC的路由規則知之甚少,所以我的麻煩就開始了。

我的目的是創建一個操作方法和URL的結構是這樣的:

http://mysite/Animals/Dogs/ViewDog/Buster

DogsController.ViewDog()看起來是這樣的:

public ActionResult ViewDog(string dogName) 
{ 
    if (dogName!= null) 
    { 
     var someDog = new DogFormViewModel(dogName); //snip a bunch more 

     return View(someDog); 
    } 
    else { return View("DogNotFound"); }   
} 

眼下的任務是確保RegisterRoutes()有正確的條目。

UPDATE

這裏的新路徑映射:

routes.MapRoute("ViewDog", "Animals/{controller}/{action}/{dogName}", 
            new { controller = "Dogs", 
              action = "ViewDog", dogName = "" }); 

創建到URL鏈接:按預期的方式創建

<%= Html.RouteLink("Brown Buster", "ViewDog", new RouteValueDictionary(new { controller="Dogs", action="ViewDog", dogName="Buster" }))%>

的URL。感謝Craig Stuntz and his blog post on Html.RouteLink

http://mySite/Animals/Dogs/ViewDog/Buster

新的問題:帕拉姆dogName不皮卡從URL字符串值 「剋星」。對該方法的調用成功,但參數的計算結果爲null。

問題

你怎麼能:

  • 化妝用細繩這條路線的工作,並刪除路由的默認慣例int id我想從int改變參數的名稱。
+0

默認值是id,而不是int id。路由令牌是無類型的。 – 2009-09-24 00:26:36

+0

你的路線在什麼順序中定義?此路由是否在默認路由中帶有'id'? – 2010-02-16 17:28:15

回答

1

您確定ActionLink實際上是否與您向他們展示問題的路線匹配嗎?如果您有多條路線,我強烈建議使用RouteLink而不是ActionLink,as I explain in great detail in this post。使用RouteLink時,至少在生成URL時,不可能匹配錯誤的路由。

+0

感謝克雷格。感謝這個建議。我已經使用了它,但現在存在一個新問題,即傳遞給方法的參數爲null,即使我已經明確地將它發送到RouteLink。有什麼建議麼? – 2009-09-23 18:06:13

+0

現在,您正在匹配路線*中的錯誤路線。*獲取Phil Haack的路由調試器,查看您匹配的路線。這不是你想要的。 – 2009-09-23 18:16:58

0

默認參數「id」不一定是int。它會匹配您在操作方法中聲明的任何類型。爲什麼不只是做以下?

public ActionResult ViewDog(string id) 
{ 
    if (id!= null) 
    { 
     var someDog = new DogFormViewModel(id); //snip a bunch more 

     return View(someDog); 
    } 
    else { return View("DogNotFound"); }   
} 
相關問題