Sending multiple parameters to Actions in ASP.NET MVC

后端 未结 3 1047
温柔的废话
温柔的废话 2021-02-05 06:08

I\'d like to send multiple parameters to an action in ASP.NET MVC. I\'d also like the URL to look like this:

http://example.com/products/item/2

3条回答
  •  情书的邮戳
    2021-02-05 06:23

    If you're ok with passing things in the query string, it's quite easy. Simply change the Action method to take an additional parameter with a matching name:

    // Products/Item.aspx?id=2 or Products/Item/2
    public ActionResult Item(int id) { }
    

    Would become:

    // Products/Item.aspx?id=2&sender=1 or Products/Item/2?sender=1
    public ActionResult Item(int id, int sender) { }
    

    ASP.NET MVC will do the work of wiring everything up for you.

    If you want a clean looking URL, you simply need to add the new route to Global.asax.cs:

    // will allow for Products/Item/2/1
    routes.MapRoute(
            "ItemDetailsWithSender",
            "Products/Item/{id}/{sender}",
            new { controller = "Products", action = "Item" }
    );
    

提交回复
热议问题