在mvc3中传递多个参数

时间:2012-05-11 12:59:28

标签: asp.net-mvc-3 url

我有一个带3个参数的控制器

public ActionResult Directives(string MachineName, int ProjectId, int CompanyId)

现在,Url看起来像这样。

/Project/Directives?projectId=41&MachineName=Apple%20Macbook%20Luft

但我怎么能让它看起来像这样。

/Project/Directives/41/AppleMacbookAir/

2 个答案:

答案 0 :(得分:2)

尝试自定义路线:

routes.MapRoute(
     "Project",                                              // Route name
     "{Controller}/{Action}/{projectId}/{machineName}/{companyId}",                           
     new { controller = "Project", action = "Directives", projectId = 0, machineName = "", companyId = 0 }  // Parameter defaults
);

http://www.asp.net/mvc/tutorials/controllers-and-routing/creating-custom-routes-cs

答案 1 :(得分:1)

您可以将id作为RedirectToAction()方法的routeValues参数的一部分传递。

return RedirectToAction("Action", new { id = 99 });

这会导致重定向到Site/Controller/Action/99.

修改 要自定义网址,您必须将custom route创建为:

routes.MapRoute(  "Project", // Route name
                   "{controller}/{Action}/{ProjectId}/{MachineName}/{CompanyId}", 
                   new { controller = "Project", 
                         action = "Directives", 
                         ProjectId= 0,
                         MachineName= "",
                         CompanyId = 0 
                       }  // Parameter defaults );

如果您想要任何参数可选,请使用UrlParameter.Optional。 关注ASP.NET MVC Routing

上的Stephen Walthe文章

请参阅:RedirectToAction with parameter