我想要一个路线,有两个可选择的参数;我认为下列会的工作:

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

因此,问题:

  • 使用的三条航线的唯一方法作一个路线,有可选择的args?

  • 这些网址确定或不是,那是,你会建议一个更好的方式来做到这个吗?

有帮助吗?

解决方案

你为什么不尝试中得到默认值(如果它是不是指我.e0),这将有助于你摆脱的一个路线

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

其他提示

看起来对我很好但是我会做到这一点不同:

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}

但那只是我

你可以试试这样的:

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

我不喜欢这个作为路线似乎并不很干净但是,应该给你的是什么我觉得你想找到实现?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top