ASP.NET MVC - passing parameters to the controller

Odd picture Odd · Oct 1, 2008 · Viewed 351.3k times · Source

I have a controller with an action method as follows:

public class InventoryController : Controller
{
    public ActionResult ViewStockNext(int firstItem)
    {
        // Do some stuff
    }
}

And when I run it I get an error stating:

The parameters dictionary does not contain a valid value of type 'System.Int32' for parameter 'firstItem'. To make a parameter optional its type should either be a reference type or a Nullable type.

I had it working at one point and I decided to try the function without parameters. Finding out that the controller was not persistant I put the parameter back in, now it refuses to recognise the parameter when I call the method.

I'm using this url syntax to call the action:

http://localhost:2316/Inventory/ViewStockNext/11

Any ideas why I would get this error and what I need to do to fix it?

I've tried adding another method that takes an integer to the class it it also fails with the same reason. I've tried adding one that takes a string, and the string is set to null. I've tried adding one without parameters and that works fine, but of course it won't suit my needs.

Answer

Jarrett Meyer picture Jarrett Meyer · Oct 1, 2008

Your routing needs to be set up along the lines of {controller}/{action}/{firstItem}. If you left the routing as the default {controller}/{action}/{id} in your global.asax.cs file, then you will need to pass in id.

routes.MapRoute(
    "Inventory",
    "Inventory/{action}/{firstItem}",
    new { controller = "Inventory", action = "ListAll", firstItem = "" }
);

... or something close to that.