向ASP.NET MVC中的Actions发送多个参数

Rez*_*eza 20 .net c# asp.net-mvc

我想向ASP.NET MVC中的一个动作发送多个参数.我也希望URL看起来像这样:

http://example.com/products/item/2
Run Code Online (Sandbox Code Playgroud)

代替:

http://example.com/products/item.aspx?id=2
Run Code Online (Sandbox Code Playgroud)

我也想为发件人做同样的事情,这是当前的网址:

http://example.com/products/item.aspx?id=2&sender=1
Run Code Online (Sandbox Code Playgroud)

如何在ASP.NET MVC中使用C#实现这两个目标?

Jus*_*ner 26

如果您可以在查询字符串中传递内容,那么这很容易.只需更改Action方法,即可获取具有匹配名称的附加参数:

// Products/Item.aspx?id=2 or Products/Item/2
public ActionResult Item(int id) { }
Run Code Online (Sandbox Code Playgroud)

会成为:

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

ASP.NET MVC将为您完成所有连接工作.

如果您想要一个干净的URL,您只需要将新路由添加到Global.asax.cs:

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


Geo*_*ker 12

如果您想要一个漂亮的URL,那么将以下内容添加到您的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
);
Run Code Online (Sandbox Code Playgroud)

然后使用所需的操作:

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

public ActionResult showItem(int id, int sender)
{
    //view stuff here
}
Run Code Online (Sandbox Code Playgroud)