ASP.net MVC RouteLink 和可选的routeValues
我试图弄清楚如何有条件地设置可选的routeValue。
如果访问者点击“类别” ,
<%= Html.RouteLink("<<<","Products",new { page=(Model.Products.PageIndex) }) %>
我只显示该类别的产品,但如果没有“类别”,我会显示所有产品。
这 2 个 URL 是有效的:
/Products/Page
/Products/Page?category=cars
RouteLink 在我的寻呼机中,所以我想我可以以某种方式在寻呼机的链接中传递类别参数,以便在页面之间保留类别。 但是,我不确定如何处理未选择类别与选择类别的情况。
我知道我可以这样做:
<%= Html.RouteLink("<<<","Products",new { page=(Model.Products.PageIndex), category=cars }) %>
但是是否可以在不创建一些尴尬的 if 语句的情况下处理这两种情况?
I'm trying to figure out how to conditionally set a routeValue which is optional.
I have
<%= Html.RouteLink("<<<","Products",new { page=(Model.Products.PageIndex) }) %>
If a visitor clicks on a "category" I only show products of that category, but if there is no "category" I show all products.
These 2 URLs would be valid:
/Products/Page
/Products/Page?category=cars
The RouteLink is in my pager so I thought I could somehow pass the category parameter in the links in the pager in order to persist the category between pages. However I'm not sure how I handle the case where no category is chosen versus when a category is chosen.
I know I can do this:
<%= Html.RouteLink("<<<","Products",new { page=(Model.Products.PageIndex), category=cars }) %>
But is it possible to handle both cases without creating some awkward if statement?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这只是一个想法,但你不能只传递一个空的类别参数吗?
在您获取页面的产品控制器中,只需检查它是否存在?
或者这就是你所说的“尴尬的 if 语句”的意思?
It's merely an idea but can't you just pass an empty category parameter?
And in your productscontroller where you get the page, just check if it exists or not?
Or is that what you mean by "awkward if statement"?
如果cars变量为null或空字符串,Html.RouteLink方法将不会自动向URL添加category参数。 您不需要进行额外的检查。
If cars variable is null or empty string, Html.RouteLink method will not add category parameter to URL automatically. You don't need to do extra checking.