我想從URL中提取一個ID。我的路線是這樣的:將路由參數轉換爲整數的正確方法是什麼?
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
和動作鏈接和生成的URL看起來像這樣:
<li>@Html.ActionLink((string)link.Name, "Video", new { id = link.ID })</li>
http://localhost:57762/Video/3 // <-- generated URL
然後我們得到的控制器:
public ActionResult Video()
{
int id = Convert.ToInt32(RouteData.Values["id"].ToString());
var treatment = Treatment.Find(id);
ViewBag.Title = treatment.Name;
ViewBag.Treatment = treatment;
return View();
}
這裏的怪異的一部分:
該視圖呈現正確的一切。我整天都可以訪問ViewBag.Treatment,一切工作正常,但第二次我的瀏覽器完成加載視圖時,Visual Studio將引發此異常:
型「System.FormatException」的異常出現在mscorlib中。但沒有在用戶代碼中處理
附加信息:輸入字符串格式不正確。
據抱怨這一行:
int id = Convert.ToInt32(RouteData.Values["id"].ToString());
我在做什麼錯?
嗯,爲什麼你的ActionResult Video沒有'int id'參數?類似'public ActionResult Video(int id)' –
@RaphaëlAlthaus沒有必要 –
@RaphaëlAlthaus我不認爲我完全理解你的評論。但它看起來可能會解決我的問題。你能發表一個完整的答案嗎? – drewwyatt