当 MVC 路由触发时,在控制器中获取空参数值
首先,我是 MVC 新手,所以如果这个问题很基础,请原谅。
我使用自定义路由创建以下 URL (http://mysite/subscriber/12345),其中12345 是订户号码。我希望它在 Subscriber
控制器中运行 ShowAll
操作。我的路线正在触发并使用 Phil 的路线调试器,当我传入上面的 url 时,路由调试器显示 ID 为 12345。 我的控制器接受 int 作为 subscriberID
。当它火起来的时候, 控制器抛出错误
参数字典包含不可为空类型“System.Int32”的参数“id”的空条目。
为什么路由调试器显示一个值而控制器看不到它?
这是我的路由(第一个是罪魁祸首)
routes.MapRoute(
"SubscriberAll",
"subscriber/{id}",
new { controller = "Subscriber", action = "ShowAll", id=0 },
new { id = @"\d+" } //confirm numeric
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
知道为什么我在 ShowAll
操作中得到 null 吗?这是操作方法签名:
public ActionResult ShowAll(int id)
First off, I'm new to MVC, so please excuse the question if it's basic.
I'm using a custom route to create the following URL (http://mysite/subscriber/12345) where 12345 is the subscriber number. I want it to run the ShowAll
action in the Subscriber
controller. My route is firing and using Phil's route debugger, when I pass in the above url, the route debugger shows ID as 12345.
My controller is accepting an int as subscriberID
. When it fires,
the controller throws the error
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32".
Why does the route debugger show a value and the controller doesn't see it?
Here's my route (first one is the culprit)
routes.MapRoute(
"SubscriberAll",
"subscriber/{id}",
new { controller = "Subscriber", action = "ShowAll", id=0 },
new { id = @"\d+" } //confirm numeric
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
Any idea why I'm getting a null in the ShowAll
action? Here is the action method signature:
public ActionResult ShowAll(int id)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
发现控制器方法签名需要接受一个字符串,因为 MVC 不知道传递参数是什么类型,因此无法将其强制转换为 int,但它可以通过约束强制执行。
所以,我最终的路线是这样的:
我最终得到的控制器方法签名是这样的
Found that the controller method signature needs to accept a string as MVC doesn't know what type the passing parameter is and therefore can't cast it to int, but it can enforce it through the constraint.
So, the route I ended up with is this:
and the controller method signature I ended up with is this
尝试从默认值列表中删除 id,即只有
Try removing id from the list of defaults ie just have
不要在 MapRoute 中写入“id = 0”,而是写入“id = UrlParameter.Optional”,
这肯定会与您的操作结果配合使用
Instead of writing "id = 0" in your MapRoute write "id = UrlParameter.Optional"
this would definitely work with your action result