asp.net-mvc – 在MVC3中使用两个可选参数的路由不起作用

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 在MVC3中使用两个可选参数的路由不起作用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的应用程序中使用了以下类型的URL.

localhost/admin/userdetail/id

localhost/admin/userdetail/id/true

localhost/admin/userdetail/id/true/success

这是我的管理员控制器

bool inSaveAction,string status are optional

[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" });
    }

Below case is not working

@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操作的可选参数?

解决方法

您错过了路线配置中的参数.为了使这个工作具有可选的不同参数(如在Phil Haack的帖子中),您需要定义多个路径
routes.MapRoute("UserDetail-WithStatus","UserDetail/{id}/{inSaveAction}/{status}",new
                 {
                     controller = "Admin",// nothing optional 
                 }
);

routes.MapRoute("UserDetail-WithoutStatus","UserDetail/{id}/{inSaveAction}",// nothing optional 
                 }
);

routes.MapRoute("UserDetail-WithoutSaveAction",id = UrlParameter.Optional
                 }
);

然后创建链接

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

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

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

}
原文链接:https://www.f2er.com/aspnet/245185.html

猜你在找的asp.Net相关文章