Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 674
Bill Martin Avatar asked Jan 12 '11 16:01

Bill Martin


2 Answers

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)
like image 59
Bill Martin Avatar answered Nov 15 '22 04:11

Bill Martin


Try removing id from the list of defaults ie just have

new { controller = "Subscriber", action = "ShowAll" }
like image 40
Vadim Avatar answered Nov 15 '22 06:11

Vadim