向ASP.NET MVC中的Actions发送多个参数
我想向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#完成这两项工作?
如果您可以在查询字符串中传递内容,那么这很容易。 只需更改Action方法,即可获取具有匹配名称的附加参数:
// 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.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" } );
如果您想要一个漂亮的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 }
您可以使用任何路由规则,例如:
{controller}/{action}/{param1}/{param2}
你也可以使用get params :baseUrl?param1=1¶m2=2
并检查此链接 ,我希望它会对你有所帮助。