ASP.NET MVC - passing parameters to the controller

后端 未结 10 1293
小蘑菇
小蘑菇 2020-11-28 23:36

I have a controller with an action method as follows:

public class InventoryController : Controller
{
    public ActionResult ViewStockNext(int firstItem)
           


        
相关标签:
10条回答
  • 2020-11-29 00:11

    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.

    0 讨论(0)
  • 2020-11-29 00:12

    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)

    0 讨论(0)
  • 2020-11-29 00:15

    or do it with Route Attribute:

    public class InventoryController : Controller
    {
        [Route("whatever/{firstItem}")]
        public ActionResult ViewStockNext(int firstItem)
        {
            int yourNewVariable = firstItem;
            // ...
        }
    }
    
    0 讨论(0)
  • 2020-11-29 00:16

    To rephrase Jarret Meyer's answer, you need to change the parameter name to 'id' or add a route like this:

    routes.MapRoute(
            "ViewStockNext", // Route name
            "Inventory/ViewStockNext/{firstItem}",  // URL with parameters
            new { controller = "Inventory", action = "ViewStockNext" }  // Parameter defaults
        );
    

    The reason is the default route only looks for actions with no parameter or a parameter called 'id'.

    Edit: Heh, nevermind Jarret added a route example after posting.

    0 讨论(0)
提交回复
热议问题