Getting null parameter value in controller when an MVC route fires
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)
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:
routes.MapRoute( "SubscriberAll", "subscriber/{id}", new {controller = "Subscriber", action = "ShowAll" }, new {id = @"\d+" } //confirm numeric );
and the controller method signature I ended up with is this
public ActionResult ShowAll(string id)
Try removing id from the list of defaults ie just have
new { controller = "Subscriber", action = "ShowAll" }
Instead of writing "id = 0" in your MapRoute write "id = UrlParameter.Optional"
this would definitely work with your action result
public ActionResult ShowAll(int id)
routes.MapRoute(
"SubscriberAll",
"subscriber/{id}",
new { controller = "Subscriber", action = "ShowAll", id = UrlParameter.Optional },
new { id = @"\d+" } //confirm numeric
);
精彩评论