问题描述
我想将多个参数发送到ASP.NET MVC中的一个动作.我也希望URL看起来像这样:
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
代替:
http://example.com/products/item.aspx?id=2
我也想对发件人进行同样的操作,这是当前的URL:
I'd like to do the same for sender as well, here's the current URL:
http://example.com/products/item.aspx?id=2&sender=1
如何在ASP.NET MVC中使用C#完成这两项工作?
How do I accomplish both with C# in ASP.NET MVC?
推荐答案
如果您可以在查询字符串中传递内容,则非常简单.只需将Action方法更改为采用具有匹配名称的其他参数即可:
If you're ok with passing things in the query string, it's quite easy. Simply change the Action method to take an additional parameter with a matching name:
// 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将为您完成所有工作.
ASP.NET MVC will do the work of wiring everything up for you.
如果您想要一个干净的URL,只需将新路由添加到Global.asax.cs:
If you want a clean looking URL, you simply need to add the new route to Global.asax.cs:
// will allow for Products/Item/2/1
routes.MapRoute(
"ItemDetailsWithSender",
"Products/Item/{id}/{sender}",
new { controller = "Products", action = "Item" }
);
这篇关于将多个参数发送到ASP.NET MVC中的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!