在MVC3中使用两个可选参数的路由不起作用

时间:2013-01-05 07:46:14

标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-routing url-routing

我的应用程序中使用了以下类型的URL。

  

本地主机/管理/ userdetail / ID

     

本地主机/管理/ userdetail / ID /真

     

本地主机/管理/ userdetail / ID /真/成功

这是我的管理员控制器

  

bool inSaveAction,字符串状态是可选的

    [Authorize]
    public ActionResult UserDetail(string Id, bool inSaveAction, string status)
    {
    }

    [HttpPost, Authorize, ValidateAntiForgeryToken]
    public ActionResult SaveUserDetail(UserDetailViewModel viewModel)
    {
        User userToSave = new User();
        AdminService.UpdateUser(userToSave);
        //This is calling the above function as it sending all 3 params
        return RedirectToAction("UserDetail", new { Id = viewModel.Id, 
                           inSaveAction = true, status = "success" });
    }
  

以下案例无效

  @Html.ActionLink("DisplayName", "UserDetail", new { id = Model.Id })

在Global.asax

 routes.MapRoute("UserDetail",
            "UserDetail/{id}",
            new
            {
                controller = "Admin",
                action = "UserDetail",
                id = UrlParameter.Optional
            }
         );

我关注http://haacked.com/archive/2011/02/20/routing-regression-with-two-consecutive-optional-url-parameters.aspx

如何制作inSaveAction& status是我的UserDetail操作的可选参数吗?

2 个答案:

答案 0 :(得分:9)

您缺少路线配置中的参数。为了使这个工作与不同的参数可选(如Phil Haack的帖子),你需要定义多个路线

routes.MapRoute("UserDetail-WithStatus", 
                "UserDetail/{id}/{inSaveAction}/{status}", 
                 new
                 {
                     controller = "Admin",
                     action = "UserDetail",
                     // nothing optional 
                 }
);

routes.MapRoute("UserDetail-WithoutStatus", 
                "UserDetail/{id}/{inSaveAction}", 
                 new
                 {
                     controller = "Admin",
                     action = "UserDetail",
                     // nothing optional 
                 }
);

routes.MapRoute("UserDetail-WithoutSaveAction", 
                "UserDetail/{id}", 
                 new
                 {
                     controller = "Admin",
                     action = "UserDetail",
                     id = UrlParameter.Optional
                 }
);

然后创建链接:

@Html.ActionLink("Link", "Index", "Admin", new { id = 1, inSaveAction = true, success = "success" }, null)

您还需要将可选参数设置为可为空,否则如果缺少id或inSaveAction,您将获得异常。

public ActionResult UserDetail(int? id, bool? inSaveAction, string status)
{

}

答案 1 :(得分:1)

您可以使用here引入的方法。它允许您定义一个这样的路线

routes.MapRoute(name: "UserDetail-WithStatus", 
            url: "UserDetail/{id}/{inSaveAction}/{status}", 
             defaults: new
             {
                 controller = "Admin",
                 action = "UserDetail",
                 // nothing optional 
             }, 
             lookupParameters:new string[] { "id", "inSaveAction", "status" },
             routeValueService: new RouteValueService()

);