【发布时间】:2014-03-26 16:10:52
【问题描述】:
我正在尝试从 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 }
);
}
Action 链接和生成的 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 会抛出此异常:
在 mscorlib.dll 中发生了“System.FormatException”类型的异常,但未在用户代码中处理
附加信息:输入字符串的格式不正确。
它在抱怨这条线:
int id = Convert.ToInt32(RouteData.Values["id"].ToString());
我做错了什么?
【问题讨论】:
-
嗯,为什么你的 ActionResult 视频没有
int id参数?类似public ActionResult Video(int id) -
@RaphaëlAlthaus 没必要
-
@RaphaëlAlthaus 我不认为我完全理解你的评论。但看起来它可以解决我的问题。你能发布一个完整的答案吗?
-
@Selman22 什么不需要?
-
@anwyatt 定义了一个参数(我对 Raphael 说过),因为您已经在 routeconfig 中定义了它。我认为应该可以工作。
标签: c# asp.net-mvc model-binding