我想向ASP.NET MVC中的一个动作发送多个参数。我也希望网址看起来像这样:
http://example.com/products/item/2
而不是:
http://example.com/products/item.aspx?id=2
我也想为发件人做同样的事情,这是当前的网址:
http://example.com/products/item.aspx?id=2&sender=1
如何在ASP.NET MVC中使用C#完成这两项工作?
答案 0 :(得分:26)
如果你可以在查询字符串中传递内容,那就很容易了。只需更改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" }
);
答案 1 :(得分:12)
如果您想要一个漂亮的网址,请将以下内容添加到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
}
答案 2 :(得分:4)
您可以使用任何路线规则,例如:
{controller}/{action}/{param1}/{param2}
你也可以使用像:baseUrl?param1=1¶m2=2
并检查this link,我希望它会对您有所帮助。