带有可选args的ASP.NET MVC自定义路由

时间:2009-09-10 08:44:56

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

我想要一个带有两个可选args的Route;我认为以下内容可行:

routes.MapRoute(
    "ProductForm",
    "products/{action}/{vendor_id}_{category_id}",
    new { controller = "Products", action = "Index", vendor_id = "", category_id = "" },
    new { action = @"Create|Edit" }
);

但只有在提供vendor_idcategory_id时才有效;使用RouteDebug我看到/products/create/_3没有触发我的路线,所以我添加了其他两条路线:

routes.MapRoute(
    "ProductForm1",
    "{controller}/{action}/_{category_id}",
    new { controller = "Home", action = "Index", category_id = "" },
    new { controller = "Products", action = @"Create|Edit" }
);

routes.MapRoute(
    "ProductForm2",
    "{controller}/{action}/{vendor_id}_",
    new { controller = "Home", action = "Index", vendor_id = "" },
    new { controller = "Products", action = @"Create|Edit" }
);

所以,问题:

  • 使用三条路线是制作带有可选参数的路线的唯一方法吗?

  • 这些网址是否正常,也就是说,您会建议更好的方法吗?

3 个答案:

答案 0 :(得分:1)

为什么不尝试给vendor_id一个默认值(如果没有指定,即0),这将有助于你摆脱一条路线

routes.MapRoute("ProductForm","products/{action}/{vendor_id}_{category_id}",
new { controller = "Products", action = "Index", vendor_id = "0", category_id = "" },   
new { action = @"Create|Edit" });

答案 1 :(得分:0)

看起来对我好,但我会做的有点不同:

routes.MapRoute(
"ProductForm1",
"product/category/{category_id}",
new { controller = "Home", action = "Index", category_id = "" },
new { controller = "Products", action = @"Create|Edit" }

);

然后

 routes.MapRoute(
"ProductForm1",
"product/details/{product_id}",
new { controller = "Home", action = "Index", product_id = "" },
new { controller = "Products", action = @"Create|Edit" }

);

那么你的课程可以如下:

ActionResults Index(){}
ActionResults Index(int category_id){// get categories}
ActionResults Index(int product_id){ // get products}

但那只是我

答案 2 :(得分:0)

你可以这样试试:

routes.MapRoute(    
"ProductForm",
"products/{action}/{arg1}/{arg1_id}/{arg2}/{arg2_id}",    
new { controller = "Products", action = "Index", arg1 = "", arg2 = "", arg1_id = "", arg2_id = "" },
new { action = @"Create|Edit" });

然后你会在你的actionresult方法中创建一些逻辑来检查arg1和arg2并识别已经传入的参数。

您的actionlink网址如下所示:

/products/create/vendor/10
/products/create/category/20
/products/create/vendor/10/category/20
/products/create/category/20/vendor/10

我个人不喜欢这个,因为这条路线看起来不是很干净,但应该给你我认为你想要达到的目标吗?