ASP.NET MVC 中的嵌套服务器端块?

发布于 2024-07-27 14:41:16 字数 1350 浏览 9 评论 0原文

最近,我一直在努力解决 ASP.NET MVC 上的一个恼人的情况。 这是简短的故事,
我应该有一个列出所有产品的视图; 现在因为这些产品太多了,我正在分页它们(非常有创意嘿!)。 该页面包含两个分页箭头 -“下 10 个产品”、“和前 10 个产品”。 该视图将传递一个 IEnumerable 集合,其中包含要显示的产品列表。 该视图还传递两个整数(currentPage、totalPages)作为 ViewData 项。 现在我需要完成的是检查它是否是第一页(ViewData["CurrentPage"] == 0)我应该将“前10页”链接的css类更改为禁用,所以我想出了类似的东西以下

 <a href="/Products/Page<%=Html.Encode(Convert.ToInt32(ViewData["CurrentPage"])-1)%>/" 
           class="<%=Convert.ToInt32(ViewData["CurrentPage"]) <= 1 ? "bgn disabled" : ""%>">                          
                previous 10 products                
        </a>

这工作正常,但仍然有问题。 尽管链接已禁用或特别变灰,但它仍然指向有效的 URL,因此我尝试根据 CurrentPage 变量实际更改链接的 href 属性。 下面是代码的样子(准备好迎接纯粹的丑陋):

<a href="<%=Convert.ToInt32(ViewData["CurrentPage"]) <= 0 ? 
        "javascript:void[]" : 
        "/products/Page<%=Html.Encode(Convert.ToInt32(ViewData["CurrentPage"])+1)%>/" %>" 
        class="<%=Convert.ToInt32(ViewData["CurrentPage"]) <= 0 ? 
        "bgn disabled" :
        ""%>">

    previous 10 products
    </a>

现在,我对这段代码的问题是:

  1. 第二个语句不起作用,显然是因为嵌套的服务器端
  2. 脚本非常丑陋,而且绝对不可读(想象一下我对每个需要分页的页面都这样做!但痛苦)。 :(

大家还有更好的选择吗?

Lately, I'v been struggling with an annoying situation on ASP.NET MVC. Here's the story in short,
I'm supposed to have a view that lists all of the products; now because those products are too many, I'm paging them (very innovative heh!). The page contains two paging arrows -"Next 10 products", "and previous 10 products". The view is passed a IEnumerable<Product> collection containing the list of products to be displayed. The view is also passed two integers (currentPage, totalPages) as ViewData items. Now what I need to accomplish is to check if it's the first page (ViewData["CurrentPage"] == 0) I should change the css class of the "previous 10 pages" link to disabled, so I came up with something like the following

 <a href="/Products/Page<%=Html.Encode(Convert.ToInt32(ViewData["CurrentPage"])-1)%>/" 
           class="<%=Convert.ToInt32(ViewData["CurrentPage"]) <= 1 ? "bgn disabled" : ""%>">                          
                previous 10 products                
        </a>

This worked fine, still there's a problem. Though the link is disabled, or specifically grayed, it still points to a valid URL, so I tried to actually change the href attribute of the link based on the CurrentPage variable. Here's how the code looks like (get ready to the pure ugliness):

<a href="<%=Convert.ToInt32(ViewData["CurrentPage"]) <= 0 ? 
        "javascript:void[]" : 
        "/products/Page<%=Html.Encode(Convert.ToInt32(ViewData["CurrentPage"])+1)%>/" %>" 
        class="<%=Convert.ToInt32(ViewData["CurrentPage"]) <= 0 ? 
        "bgn disabled" :
        ""%>">

    previous 10 products
    </a>

Now, my problems with this code are:

  1. The second statement doesn't work, apparently because of the nested server side scripts
  2. It's very ugly, and absolutely unreadable (imagine I'm doing this with each page that requires paging! pain in the but). :(

Any better alternatives guys?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

夕色琉璃 2024-08-03 14:41:16

您可以使用 if 语句:

<% if (Convert.ToInt32(ViewData["CurrentPage"]) <= 0) { %>
     Disabled template goes here...
<% } else { %> 
     Link template goes here...
<% } %>

顺便说一句,如果您要对一组页面执行此操作,则可以将其封装在 ViewUserControlViewMasterPage 中

You can use an if statement:

<% if (Convert.ToInt32(ViewData["CurrentPage"]) <= 0) { %>
     Disabled template goes here...
<% } else { %> 
     Link template goes here...
<% } %>

By the way, if you're doing this for a set of pages, you can encapsulate it in a ViewUserControl or a ViewMasterPage.

追我者格杀勿论 2024-08-03 14:41:16

这是另一个解决方案。 添加

<script runat="server">
    protected string Prev10Url {
        get {
            return Convert.ToInt32(ViewData["CurrentPage"]) <= 0
                ? "javascript:void[]"
                : "/products/Page" + Html.Encode(Convert.ToInt32(ViewData["CurrentPage"])+1);
        }
    }

    protected string Prev10Class {
        get {
            return Convert.ToInt32(ViewData["CurrentPage"]) <= 0
                ? "bgn disabled"
                : "";
        }
    }

    protected string Next10Url {
        get {
            ...
        }
    }

    protected string Next10Class {
        get {
            ...
        }
    }
</script>

然后更改您的标记:

<a href="<%= Prev10Url %>" class="<%= Prev10Class %>">previous 10 products</a>
<a href="<%= Next10Url %>" class="<%= Next10Class %>">next 10 products</a>

Here is another solution. Add <script runat="server">:

<script runat="server">
    protected string Prev10Url {
        get {
            return Convert.ToInt32(ViewData["CurrentPage"]) <= 0
                ? "javascript:void[]"
                : "/products/Page" + Html.Encode(Convert.ToInt32(ViewData["CurrentPage"])+1);
        }
    }

    protected string Prev10Class {
        get {
            return Convert.ToInt32(ViewData["CurrentPage"]) <= 0
                ? "bgn disabled"
                : "";
        }
    }

    protected string Next10Url {
        get {
            ...
        }
    }

    protected string Next10Class {
        get {
            ...
        }
    }
</script>

And then change your markup:

<a href="<%= Prev10Url %>" class="<%= Prev10Class %>">previous 10 products</a>
<a href="<%= Next10Url %>" class="<%= Next10Class %>">next 10 products</a>
魂归处 2024-08-03 14:41:16

您可以尝试我的寻呼机 HTML 帮助器:

using System;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;

namespace System.Web.Mvc
{
   public class Pager
   {
      private ViewContext viewContext;
      private readonly int pageSize;
      private readonly int currentPage;
      private readonly int totalItemCount;
      private readonly RouteValueDictionary linkWithoutPageValuesDictionary;

      public Pager(ViewContext viewContext, int pageSize, int currentPage, int totalItemCount, RouteValueDictionary valuesDictionary)
      {
         this.viewContext = viewContext;
         this.pageSize = pageSize;
         this.currentPage = currentPage;
         this.totalItemCount = totalItemCount;
         this.linkWithoutPageValuesDictionary = valuesDictionary;
      }

      public string RenderHtml()
      {
         int pageCount = (int)Math.Ceiling(this.totalItemCount / (double)this.pageSize);
         int nrOfPagesToDisplay = 8;

         var sb = new StringBuilder();
         sb.Append("<ul class=\"pagination\">");
         // Previous
         if (this.currentPage > 1)
         {
            sb.Append(string.Format("<li class=\"prev\"><a href=\"{0}\">«</a></li>", Route(this.currentPage - 1)));
         }
         else
         {
            sb.Append("<li class=\"prev disabled\"><span>«</span></li>");
         }

         int start = 1;
         int end = pageCount;

         if (pageCount > nrOfPagesToDisplay)
         {
            int middle = (int)Math.Ceiling(nrOfPagesToDisplay / 2d) - 1;
            int below = (this.currentPage - middle);
            int above = (this.currentPage + middle);

            if (below < 4)
            {
               above = nrOfPagesToDisplay;
               below = 1;
            }
            else if (above > (pageCount - 4))
            {
               above = pageCount;
               below = (pageCount - nrOfPagesToDisplay);
            }

            start = below;
            end = above;
         }

         if (start > 3)
         {
            sb.Append(GeneratePageLink("1", 1));
            sb.Append(GeneratePageLink("2", 2));
                sb.Append("<li class=\"more\">...</li>");
         }
         for (int i = start; i <= end; i++)
         {
            if (i == this.currentPage)
            {
               sb.Append(string.Format("<li class=\"page selected\"><span>{1}</span></li>", Route(i),i));
            }
            else
            {
               sb.Append(GeneratePageLink(i.ToString(), i));
            }
         }
         if (end < (pageCount - 3))
         {
                sb.Append("<li class=\"more\">...</li>");
            sb.Append(GeneratePageLink((pageCount - 1).ToString(), pageCount - 1));
            sb.Append(GeneratePageLink(pageCount.ToString(), pageCount));
         }

         // Next
         if (this.currentPage < pageCount)
         {
            sb.Append(string.Format("<li class=\"next\"><a href=\"{0}\">»</a></li>", Route(this.currentPage + 1)));
         }
         else
         {
            sb.Append("<li class=\"next disabled\"><span>»</span></li>");
         }
         sb.Append("</ul>");
         return sb.ToString();
      }
      private string Route(int pageNumber)
      {

         var pageLinkValueDictionary = new RouteValueDictionary(this.linkWithoutPageValuesDictionary);
         pageLinkValueDictionary.Add("page", pageNumber);
         var virtualPathData = RouteTable.Routes.GetVirtualPath(this.viewContext.RequestContext, pageLinkValueDictionary);
         return virtualPathData.VirtualPath;

      }
      private string GeneratePageLink(string linkText, int pageNumber)
      {
         var pageLinkValueDictionary = new RouteValueDictionary(this.linkWithoutPageValuesDictionary);
         pageLinkValueDictionary.Add("page", pageNumber);
         var virtualPathData = RouteTable.Routes.GetVirtualPath(this.viewContext.RequestContext, pageLinkValueDictionary);

         if (virtualPathData != null)
         {

            string linkFormat = "<li class=\"page\"><a href=\"{0}\">{1}</a></li>";
            return String.Format(linkFormat, virtualPathData.VirtualPath, linkText);
         }
         else
         {
            return null;
         }
      }
   }
}

如何使用:

<%= Html.Pager(10, (Request["page"].IsNotNull() ? Request["page"].ToInt() : 1), ViewData["Total"].ToInt(), new { category = Request["category"], alphabet = Request["alphabet"] })%>

控制器实现如下所示:

public ActionResult Index(string page, string category, string alphabet)
{
   .....
   ViewData["Total"] = model.Count();
   return View(model.ToPagedList((page.IsNotNull() ? page.ToInt() - 1 : 0), 10));
}

最后输出:

pager
(来源:clip2net.com

You can try my pager HTML helper:

using System;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;

namespace System.Web.Mvc
{
   public class Pager
   {
      private ViewContext viewContext;
      private readonly int pageSize;
      private readonly int currentPage;
      private readonly int totalItemCount;
      private readonly RouteValueDictionary linkWithoutPageValuesDictionary;

      public Pager(ViewContext viewContext, int pageSize, int currentPage, int totalItemCount, RouteValueDictionary valuesDictionary)
      {
         this.viewContext = viewContext;
         this.pageSize = pageSize;
         this.currentPage = currentPage;
         this.totalItemCount = totalItemCount;
         this.linkWithoutPageValuesDictionary = valuesDictionary;
      }

      public string RenderHtml()
      {
         int pageCount = (int)Math.Ceiling(this.totalItemCount / (double)this.pageSize);
         int nrOfPagesToDisplay = 8;

         var sb = new StringBuilder();
         sb.Append("<ul class=\"pagination\">");
         // Previous
         if (this.currentPage > 1)
         {
            sb.Append(string.Format("<li class=\"prev\"><a href=\"{0}\">«</a></li>", Route(this.currentPage - 1)));
         }
         else
         {
            sb.Append("<li class=\"prev disabled\"><span>«</span></li>");
         }

         int start = 1;
         int end = pageCount;

         if (pageCount > nrOfPagesToDisplay)
         {
            int middle = (int)Math.Ceiling(nrOfPagesToDisplay / 2d) - 1;
            int below = (this.currentPage - middle);
            int above = (this.currentPage + middle);

            if (below < 4)
            {
               above = nrOfPagesToDisplay;
               below = 1;
            }
            else if (above > (pageCount - 4))
            {
               above = pageCount;
               below = (pageCount - nrOfPagesToDisplay);
            }

            start = below;
            end = above;
         }

         if (start > 3)
         {
            sb.Append(GeneratePageLink("1", 1));
            sb.Append(GeneratePageLink("2", 2));
                sb.Append("<li class=\"more\">...</li>");
         }
         for (int i = start; i <= end; i++)
         {
            if (i == this.currentPage)
            {
               sb.Append(string.Format("<li class=\"page selected\"><span>{1}</span></li>", Route(i),i));
            }
            else
            {
               sb.Append(GeneratePageLink(i.ToString(), i));
            }
         }
         if (end < (pageCount - 3))
         {
                sb.Append("<li class=\"more\">...</li>");
            sb.Append(GeneratePageLink((pageCount - 1).ToString(), pageCount - 1));
            sb.Append(GeneratePageLink(pageCount.ToString(), pageCount));
         }

         // Next
         if (this.currentPage < pageCount)
         {
            sb.Append(string.Format("<li class=\"next\"><a href=\"{0}\">»</a></li>", Route(this.currentPage + 1)));
         }
         else
         {
            sb.Append("<li class=\"next disabled\"><span>»</span></li>");
         }
         sb.Append("</ul>");
         return sb.ToString();
      }
      private string Route(int pageNumber)
      {

         var pageLinkValueDictionary = new RouteValueDictionary(this.linkWithoutPageValuesDictionary);
         pageLinkValueDictionary.Add("page", pageNumber);
         var virtualPathData = RouteTable.Routes.GetVirtualPath(this.viewContext.RequestContext, pageLinkValueDictionary);
         return virtualPathData.VirtualPath;

      }
      private string GeneratePageLink(string linkText, int pageNumber)
      {
         var pageLinkValueDictionary = new RouteValueDictionary(this.linkWithoutPageValuesDictionary);
         pageLinkValueDictionary.Add("page", pageNumber);
         var virtualPathData = RouteTable.Routes.GetVirtualPath(this.viewContext.RequestContext, pageLinkValueDictionary);

         if (virtualPathData != null)
         {

            string linkFormat = "<li class=\"page\"><a href=\"{0}\">{1}</a></li>";
            return String.Format(linkFormat, virtualPathData.VirtualPath, linkText);
         }
         else
         {
            return null;
         }
      }
   }
}

How to use:

<%= Html.Pager(10, (Request["page"].IsNotNull() ? Request["page"].ToInt() : 1), ViewData["Total"].ToInt(), new { category = Request["category"], alphabet = Request["alphabet"] })%>

And Controller implementation looks like this:

public ActionResult Index(string page, string category, string alphabet)
{
   .....
   ViewData["Total"] = model.Count();
   return View(model.ToPagedList((page.IsNotNull() ? page.ToInt() - 1 : 0), 10));
}

And finally output:

pager
(source: clip2net.com)

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