Sending multiple parameters to Actions in ASP.NET MVC

后端 未结 3 1048
温柔的废话
温柔的废话 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:19

    If you want a pretty URL, then add the following to your global.asax.cs.

    routes.MapRoute("ProductIDs",
        "Products/item/{id}",
        new { controller = Products, action = showItem, id="" }
        new { id = @"\d+" }
     );
    
    routes.MapRoute("ProductIDWithSender",
       "Products/item/{sender}/{id}/",
        new { controller = Products, action = showItem, id="" sender="" } 
        new { id = @"\d+", sender=@"[0-9]" } //constraint
    );
    

    And then to use the needed actions:

    public ActionResult showItem(int id)
    {
        //view stuff here.
    }
    
    public ActionResult showItem(int id, int sender)
    {
        //view stuff here
    }
    

提交回复
热议问题