解決方案
路線當我輸入localhost/MyController/MyActionName/1時,我在可選參數中得到一個null爲什麼?
routes.MapRoute(
"Whatever", // Route name
"{controller}/{action}/{id}", //{ID} MUST BE USED IN YOUR CONTROLLER AS THE PARAMETER
new { controller = "MyController", action = "MyActionName", id = UrlParameter.Optional } // Parameter defaults
);
就是這樣!我猜你一定在 公衆的ActionResult使用名稱的ID(INT ID //必須是ID喜歡這裏的Global.asax)
Steps to reproduce my problem: 1. Create a new mvc3 application 2. Go to home controller and put Index(int? x){ return view()} 3. Run the application 4. Go to the url type in the url http://localthost:someport/Home/Index/1 5. Insert a break point in controller to see the value of x 6. Notice that even if you put the url above x NOT equal to 1 as is suppose to!
我只是不明白爲什麼我的ID得到一個空....
public ActionResult MyActionName(int? id)
{
//the id is null!!!!!!!!!!!! event thought i just entered the url below!
}
我在瀏覽器 http://locahost/MyController/MyActionName/1
輸入以下網址//我也把這個在我的Global.asax,但它並不真正的幫助。
routes.MapRoute(
"Whatever", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "MyController", action = "MyActionName", id = UrlParameter.Optional } // Parameter defaults
);
AND! 我的錯誤,如果我把
public ActionResult MyActionName(int id)
{
//the id is null!!!!!!!!!!!! event thought i just entered the url below!
}
注意上面的例子是爲了簡單做出這個錯誤是實際應用。
'/'應用程序中的服務器錯誤。
對於'MedicalVariance.Controllers.MedicineManagementController'中的方法'System.Web.Mvc.ActionResult Index(Int32)',參數字典包含一個空的條目,用於參數'MvrId'的非空值類型'System.Int32'。可選參數必須是引用類型,可爲空類型,或者聲明爲可選參數。 參數名稱:參數 描述:執行當前Web請求期間發生未處理的異常。請查看堆棧跟蹤以獲取有關該錯誤的更多信息以及源代碼的位置。
異常詳細信息:System.ArgumentException:參數字典中的方法'System.Web.Mvc.ActionResult Index(Int32)'中的'非空'類型'System.Int32'的參數'MvrId' MedicalVariance.Controllers.MedicineManagementController」。可選參數必須是引用類型,可爲空類型,或者聲明爲可選參數。 參數名稱:參數
這是你在你的global.asax中唯一的路線嗎?請顯示您的整個RegisterRoutes和Application_Start方法。這可能有幫助。 – hatchet 2012-01-05 22:10:08
你可以發佈你用來檢查id爲空的代碼嗎?你是否已經驗證過你的行爲中的代碼實際上是在執行? – 2012-01-05 22:35:07
-1。這個問題還不清楚。這些步驟不允許我重現錯誤。我不確定在步驟6中我應該注意什麼。第4步討論Home/Index網址,而下一個URL和路由提到了MyController/MyActionName。你已經討論過其他路線,但是當你沒有提供他們的成員提問時。並且您提供了一條似乎不相關的錯誤消息。 – Dangerous 2012-01-05 23:03:28