C# 在ASP.NET MVC中将多个参数发送到操作

C# 在ASP.NET MVC中将多个参数发送到操作,c#,.net,asp.net-mvc,C#,.net,Asp.net Mvc,我想向ASP.NET MVC中的一个操作发送多个参数。我还希望URL如下所示: http://example.com/products/item/2 而不是: http://example.com/products/item.aspx?id=2 我也希望对发件人执行同样的操作,以下是当前的URL: http://example.com/products/item.aspx?id=2&sender=1 如何在ASP.NET MVC中使用C#实现这两个功能?如果您不介意在查询字符串中传

我想向ASP.NET MVC中的一个操作发送多个参数。我还希望URL如下所示:

http://example.com/products/item/2
而不是:

http://example.com/products/item.aspx?id=2
我也希望对发件人执行同样的操作,以下是当前的URL:

http://example.com/products/item.aspx?id=2&sender=1

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

如果您不介意在查询字符串中传递内容,那么这非常简单。只需更改操作方法以获取具有匹配名称的附加参数:

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

// Products/Item.aspx?id=2&sender=1 or Products/Item/2?sender=1
public ActionResult Item(int id, int sender) { }
ASP.NETMVC将为您完成所有连接工作

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

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

您可以使用任何路由规则,例如:

{controller}/{action}/{param1}/{param2}
您还可以使用get参数,如
:baseUrl?param1=1¶m2=2


请检查,我希望它能帮助您。

如果您想要一个漂亮的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
);
然后使用所需的操作:

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

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

不要忘记在global.asax中为路由设置适当的定义。@Reza-我已经在代码中添加了URL作为注释。如果您想要更清晰的URL,则需要向global.asax.cs添加自定义路由。