带有可选参数的 ASP.NET MVC 自定义路由
我想要一个带有两个可选参数的路线;我认为以下内容可行:
routes.MapRoute(
"ProductForm",
"products/{action}/{vendor_id}_{category_id}",
new { controller = "Products", action = "Index", vendor_id = "", category_id = "" },
new { action = @"Create|Edit" }
);
但只有在同时提供 vendor_id
和 category_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" }
);
所以,问题:
正在使用三个路由是创建具有可选参数的路由的唯一方法吗?
这些 URL 是否可以,也就是说,您是否会建议一个更好的方法来执行此操作?
这些
I want a Route with two optional args; I thought the following would work:
routes.MapRoute(
"ProductForm",
"products/{action}/{vendor_id}_{category_id}",
new { controller = "Products", action = "Index", vendor_id = "", category_id = "" },
new { action = @"Create|Edit" }
);
But it only works when both vendor_id
and category_id
are provided; using RouteDebug
I see that /products/create/_3
doesn't trigger my route, so I added other two routes:
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" }
);
So, the questions:
Is using three routes the only way to make a route with optional args?
Are these URLs ok or not, that is, would you suggest a better way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你为什么不尝试给vendor_id一个默认值(如果没有指定,即0),这将帮助你摆脱一条路线
Why don't you try to give vendor_id a default value (if it is not specified i.e 0) that would help you get away with one route
对我来说看起来不错,但我会做一些不同的
:);
进而
);
那么你的课程可以如下:
但这就是我
looks good to me but i would do it a little different:
);
and then
);
then your class can be as follows:
but thats just me
你可以这样尝试:
然后你会在你的actionresult方法中创建一些逻辑来检查arg1和arg2并识别已传入的参数。
你的actionlink url将如下所示:
就我个人而言,我不喜欢这样,因为路由不看起来很干净,但应该给你我认为你想要实现的目标?
you could try it like this:
Then you would create some logic in your actionresult method to check arg1 and arg2 and identify wich argument has been passed in.
your actionlink urls would look like this:
Personally i dont like this as the route doesn't seem very clean but should give you what i think your looking to achieve?