ASP.net MVC RouteLink 和可选的routeValues

发布于 2024-07-21 06:27:11 字数 601 浏览 3 评论 0原文

我试图弄清楚如何有条件地设置可选的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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

烟酉 2024-07-28 06:27:11

这只是一个想法,但你不能只传递一个空的类别参数吗?

<%= Html.RouteLink("<<<","Products",new { page=(Model.Products.PageIndex), category=(ViewData["CategoryName"]) }) %>

在您获取页面的产品控制器中,只需检查它是否存在?

public ActionResult Index(int page, string category)
{
    ViewData["CategoryName"] = category;

    if(!string.IsNullOrEmpty(category)){
        //paging with category
    }else{
        //paging without category
    }
    return View("Create");
}

或者这就是你所说的“尴尬的 if 语句”的意思?

It's merely an idea but can't you just pass an empty category parameter?

<%= Html.RouteLink("<<<","Products",new { page=(Model.Products.PageIndex), category=(ViewData["CategoryName"]) }) %>

And in your productscontroller where you get the page, just check if it exists or not?

public ActionResult Index(int page, string category)
{
    ViewData["CategoryName"] = category;

    if(!string.IsNullOrEmpty(category)){
        //paging with category
    }else{
        //paging without category
    }
    return View("Create");
}

Or is that what you mean by "awkward if statement"?

最单纯的乌龟 2024-07-28 06:27:11

如果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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文