Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - passing parameters to the controller

Tags:

c#

asp.net-mvc

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.

like image 635
Odd Avatar asked Oct 01 '08 01:10

Odd


2 Answers

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.

like image 77
Jarrett Meyer Avatar answered Oct 04 '22 21:10

Jarrett Meyer


you can change firstItem to id and it will work

you can change the routing on global.asax (i do not recommed that)

and, can't believe no one mentioned this, you can call :

http://localhost:2316/Inventory/ViewStockNext?firstItem=11 

In a @Url.Action would be :

@Url.Action("ViewStockNext", "Inventory", new {firstItem=11}); 

depending on the type of what you are doing, the last will be more suitable. Also you should consider not doing ViewStockNext action and instead a ViewStock action with index. (my 2cents)

like image 34
Bart Calixto Avatar answered Oct 04 '22 20:10

Bart Calixto