带可选参数的MVC路由

Ill*_*ova 4 asp.net-mvc routing asp.net-mvc-3

我有这条路线设置:

routes.MapRoute(
    "home3", // Route name
    "home3/{id}", // URL with parameters
    new { 
        controller = "home", 
        action = "Index", 
        id = UrlParameter.Optional } // Parameter defaults
);
Run Code Online (Sandbox Code Playgroud)

但在我的控制器中,我不知道如何获得可选的id参数.有人可以解释我如何访问它以及我如何处理它存在或不存在.

谢谢

Muh*_*hid 16

你可以写你的动作方法

public ActionResult index(int? id)
{
   if(id.HasValue)
   {
       //do something  
   }
   else
   {
      //do something else
   }
}
Run Code Online (Sandbox Code Playgroud)

  • 只需快速说明,您也可以使用C#4的可选参数.这意味着你将拥有`public ActionResult index(int id = 0)`. (3认同)

Rob*_*nik 8

如何避免可为空的动作参数(和if语句)

正如您在@ Muhammad的回答中看到的那样(BTW是一个被接受为正确答案的人),很容易将可选参数(实际上任何路由参数)转换为控制器动作.所有你必须确保它们是可空的(因为它们是可选的).

但由于它们是可选的,因此最终会出现分支代码,这对于维护单元测试更加困难.因此,通过使用一个简单的动作方法选择器,可以编写类似于此的东西:

public ActionResult Index()
{
    // do something when there's not ID
}

[RequiresRouteValues("id")]
public ActionResult Index(int id) // mind the NON-nullable parameter
{
    // do something that needs ID
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下使用了自定义操作方法选择器,您可以在我的博客文章中找到它的代码和详细说明.这些动作很容易掌握/理解,单元测试(没有不必要的分支)和维护.