我真的很生气。
以下是我的Global.asax
中的内容routes.MapRoute("BlogDetails", "Blogs/{id}/{title}", new { controller = "Blogs", action = "Details", id = "" });
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
这是我唯一的两条路线。
当我尝试访问
时http://mysite/Blogs/Edit/1 它不起作用我收到此错误
参数字典包含非可空类型'System.Int32'的参数'id'的空条目,用于'mysite.Controllers.BlogsController'中方法'System.Web.Mvc.ActionResult Details(Int32)'。可选参数必须是引用类型,可空类型,或者声明为可选参数。
为什么会这种情况继续发生?
由于
我还应该添加我的控制器代码,如下所示
//
// GET: /Blogs/Edit/5
[Authorize]
public ActionResult Edit(int id)
{
// do a bunch of stuff and return something
}
答案 0 :(得分:5)
尝试以下
routes.MapRoute("BlogDetails", "Blogs/{id}/{title}",
new { controller = "Blogs", action = "Details"},
new { id = @"\d+" });
就MVC路由而言,{id}
可以是任何东西(甚至是字符串),因此它将Edit
与字符串匹配,而不能进入id
的{{1}}你的行动。
添加new { id= @"\d+" }
作为额外参数告诉路由系统仅匹配数字。
http://www.asp.net/(S(pdfrohu0ajmwt445fanvj2r3))/learn/mvc/tutorial-24-cs.aspx
答案 1 :(得分:1)
您拥有的2条路线实际上是“ confilicting ”,在您的情况下,第一条路线会被选中而不是第二条路线。
也许您需要修改路线以消除歧义:
routes.MapRoute("BlogDetails", "Blogs/{id}-{title}", new { controller = "Blogs", action = "Details", id = "" });
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
此定义将明确区分:http://mysite/Blogs/Edit/1
和http://mysite/Blogs/1-first
或正如Baddie所提到的那样尝试在路线上添加约束。