Formatting an asp:DataPager to show in ul li

2019-03-09 12:41发布

I am building a website using the Twitter Bootstrap and ASP.Net C# Webforms. I have a ListView on my page with a DataPager bound to it, but I need to change the way .Net renders the HTML of the DataPager.

Currently, all pager items are displaying like this:

<div class="clearfix pagination pagination-centered"> <span id="cpBody_dpListing"> <a class="aspNetDisabled">First</a>&nbsp;<span>1</span>&nbsp; <a href="javascript:__doPostBack('ctl00$cpBody$dpListing$ctl02$ctl01','')">2</a>&nbsp; <a href="javascript:__doPostBack('ctl00$cpBody$dpListing$ctl03$ctl00','')">Last</a>&nbsp; </span> </div>

however I need to wrap all my items in an unordered list rather than span and a tags. My current mark-up looks like this:

<div class="clearfix pagination pagination-centered">
<asp:DataPager ID="dpListing" runat="server" PagedControlID="lvListing" PageSize="10" OnPreRender="dpListing_PreRender">
    <Fields>
        <asp:TemplatePagerField>
            <PagerTemplate>
                <asp:BulletedList ID="listPages" runat="server" DisplayMode="LinkButton" OnClick="listPages_Click"></asp:BulletedList>
            </PagerTemplate>
        </asp:TemplatePagerField>
        <asp:NextPreviousPagerField ButtonType="Link" ShowFirstPageButton="true" ShowNextPageButton="false" ShowPreviousPageButton="false" />
        <asp:NumericPagerField PreviousPageText="&lt; Prev 10" NextPageText="Next 10 &gt;" ButtonCount="10" />
        <asp:NextPreviousPagerField ButtonType="Link" ShowLastPageButton="true" ShowNextPageButton="false" ShowPreviousPageButton="false" />
    </Fields>
</asp:DataPager>

I somehow need to override the NextPreviousPagerField and NumericPagerField so they output <li> tags rather than <span> and <a>.

4条回答
萌系小妹纸
2楼-- · 2019-03-09 12:55

I have a slightly different solution to this. Instead of changing the rendering of the DataPager, I have slightly adapted the markup, and in terms of rendering, it still looks "bootstrap-like", even though it doesn't have the UL/LI tags with pagination class.

A very important thing (as explained in https://stackoverflow.com/a/19398488/1948625) is changing the class asp.net outputs for disabled control, it defaults to "aspNetDisabled" but for bootstrap it's much better to simply use "disabled". Do this in Application_Start in the Global.asax. If you don't, the first page, previous page, next page and last page buttons don't appear disabled.

void Application_Start(object sender, EventArgs e)
{
    WebControl.DisabledCssClass = "customDisabledClassName";
}

Source: WebControl.DisabledCssClass Property (MSDN)

    <asp:DataPager ID="it" runat="server" class="btn-group btn-group-sm">
        <Fields>
            <asp:NextPreviousPagerField PreviousPageText="<" FirstPageText="|<" ShowPreviousPageButton="true"
                ShowFirstPageButton="true" ShowNextPageButton="false" ShowLastPageButton="false"
                ButtonCssClass="btn btn-default" RenderNonBreakingSpacesBetweenControls="false" RenderDisabledButtonsAsLabels="false" />
            <asp:NumericPagerField ButtonType="Link" CurrentPageLabelCssClass="btn btn-primary disabled"  RenderNonBreakingSpacesBetweenControls="false"
                NumericButtonCssClass="btn btn-default" ButtonCount="10" NextPageText="..." NextPreviousButtonCssClass="btn btn-default" />
            <asp:NextPreviousPagerField NextPageText=">" LastPageText=">|" ShowNextPageButton="true"
                ShowLastPageButton="true" ShowPreviousPageButton="false" ShowFirstPageButton="false"
                ButtonCssClass="btn btn-default" RenderNonBreakingSpacesBetweenControls="false" RenderDisabledButtonsAsLabels="false"/>
        </Fields>
    </asp:DataPager>

Asp.net server markup above renders as this pager: asp.net server markup renders as this pager

And this is the rendered html:

<span id="ctl00_Body_CaseList918421504_ListControl_Pager_it" class="btn-group btn-group-sm">
    <a class="disabled btn btn-default">|&lt;</a>
    <a class="disabled btn btn-default">&lt;</a>
    <span class="btn btn-primary disabled">1</span>
    <a class="btn btn-default" href="javascript:__doPostBack('ctl00$Body$CaseList918421504_ListControl$Pager$it$ctl01$ctl01','')">2</a>
    <a class="btn btn-default" href="javascript:__doPostBack('ctl00$Body$CaseList918421504_ListControl$Pager$it$ctl01$ctl02','')">3</a>
    <a class="btn btn-default" href="javascript:__doPostBack('ctl00$Body$CaseList918421504_ListControl$Pager$it$ctl01$ctl03','')">4</a>
    <a class="btn btn-default" href="javascript:__doPostBack('ctl00$Body$CaseList918421504_ListControl$Pager$it$ctl01$ctl04','')">5</a>
    <a class="btn btn-default" href="javascript:__doPostBack('ctl00$Body$CaseList918421504_ListControl$Pager$it$ctl01$ctl05','')">6</a>
    <a class="btn btn-default" href="javascript:__doPostBack('ctl00$Body$CaseList918421504_ListControl$Pager$it$ctl01$ctl06','')">7</a>
    <a class="btn btn-default" href="javascript:__doPostBack('ctl00$Body$CaseList918421504_ListControl$Pager$it$ctl01$ctl07','')">8</a>
    <a class="btn btn-default" href="javascript:__doPostBack('ctl00$Body$CaseList918421504_ListControl$Pager$it$ctl01$ctl08','')">9</a>
    <a class="btn btn-default" href="javascript:__doPostBack('ctl00$Body$CaseList918421504_ListControl$Pager$it$ctl01$ctl09','')">10</a>
    <a class="btn btn-default" href="javascript:__doPostBack('ctl00$Body$CaseList918421504_ListControl$Pager$it$ctl01$ctl10','')">...</a>
    <a class="btn btn-default" href="javascript:__doPostBack('ctl00$Body$CaseList918421504_ListControl$Pager$it$ctl02$ctl00','')">&gt;</a>
    <a class="btn btn-default" href="javascript:__doPostBack('ctl00$Body$CaseList918421504_ListControl$Pager$it$ctl02$ctl01','')">&gt;|</a>
</span>
查看更多
放我归山
3楼-- · 2019-03-09 12:56

The DataPager doesn't support this out of the box, so you're going to need a custom control. Fortunately, it's quite east to implement!

For each DataPagerField, the DataPager adds a DataPagerFieldItem control to its own control collection, and then tells the field to create its controls within that item. The built-in fields will add non-breaking spaces between the buttons (unless you set the RenderNonBreakingSpacesBetweenControls property to false), but they're quite easy to identify and suppress.

This control will still render the <a> tags for the enabled buttons and the <span> tag for the current page number, but should be close to what you need:

public class UnorderedListDataPager : DataPager
{
   protected override HtmlTextWriterTag TagKey 
   {
      get { return HtmlTextWriterTag.Ul; }
   }

   protected override void RenderContents(HtmlTextWriter writer)
   {
      if (HasControls())
      {
         foreach (Control child in Controls)
         {
            var item = child as DataPagerFieldItem;
            if (item == null || !item.HasControls())
            {
                child.RenderControl(writer);
                continue;
            }

            foreach (Control button in item.Controls)
            {
               var space = button as LiteralControl;
               if (space != null && space.Text == "&nbsp;") continue;

               writer.RenderBeginTag(HtmlTextWriterTag.Li);
               button.RenderControl(writer);
               writer.RenderEndTag();
            }
         }
      }
   }
}

HTML output:

<ul id="dpListing">
   <li><a class="aspNetDisabled">First</a></li>
   <li><span>1</span></li>
   <li><a href="javascript:__doPostBack('ctl00$cpBody$dpListing$ctl02$ctl01','')">2</a></li>
   <li><a href="javascript:__doPostBack('ctl00$cpBody$dpListing$ctl03$ctl00','')">Last</a></li>
</ul>
查看更多
时光不老,我们不散
4楼-- · 2019-03-09 12:57

I've made additional changes to Andreas's answer. The Bootstrap samples wrap the current page (active) page inside of a hyperlink tag, so I've noticed that some Bootstrap templates do not format the active tag correctly when choosing a size variation such as pagination-lg or pagination-sm. Here is my version of RenderContents with the extra hyperlink wrap added:

    protected override void RenderContents(HtmlTextWriter writer)
    {
        if (HasControls())
        {
            foreach (Control child in Controls)
            {
                var item = child as DataPagerFieldItem;
                if (item == null || !item.HasControls())
                {
                    child.RenderControl(writer);
                    continue;
                }

                foreach (Control ctrl in item.Controls)
                {
                    var space = ctrl as LiteralControl;
                    if (space != null && space.Text == "&nbsp;")
                        continue;

                    // Set specific classes for li-Tag
                    var isCurrentPage = false;
                    if (ctrl is WebControl)
                    {
                        // Enabled = false -> "disabled"
                        if (!((WebControl)ctrl).Enabled)
                            writer.AddAttribute(HtmlTextWriterAttribute.Class, "disabled");

                        // there can only be one Label in the datapager -> "active"
                        if (ctrl is Label)
                        {
                            isCurrentPage = true;
                            writer.AddAttribute(HtmlTextWriterAttribute.Class, "active");
                        }
                    }

                    writer.RenderBeginTag(HtmlTextWriterTag.Li);
                    if (isCurrentPage)
                    {
                        writer.AddAttribute(HtmlTextWriterAttribute.Href, "#");
                        writer.RenderBeginTag(HtmlTextWriterTag.A);
                    }
                    ctrl.RenderControl(writer);
                    if (isCurrentPage)
                        writer.RenderEndTag();
                    writer.RenderEndTag();
                }
            }
        }
    }
查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-03-09 13:00

In addition to the answer of Richard ... I used his approach and added support for the "disabled" and "active" classes and the surrounding div-Tag-

Update: I added the suggestion of John for special rendering of the active-Label as a hyperlink for correct rendering of pagination-sm and pagination-lg. So credit and thanks to John too.

Update 2: Added rendering of id for the control. Thanks to DGibbs.

    [
    Bindable(false),
    Category("Appearance"),
    DefaultValue("pagination pagination-centered"),
    Description("Css class for the surrounding div")
    ]
    public virtual string CssClass {
        get {
            if (ViewState["CssClass"] == null) {
                ViewState["CssClass"] = "pagination pagination-centered";
            }
            return (string)ViewState["CssClass"];
        }
        set {
            ViewState["CssClass"] = value;
        }
    }

    protected override HtmlTextWriterTag TagKey {
        get {
                return HtmlTextWriterTag.Div;
        }
    }

    protected override void AddAttributesToRender(HtmlTextWriter writer) {
            if (HasControls()) {
                writer.AddAttribute("id", base.ClientID);
                writer.AddAttribute(HtmlTextWriterAttribute.Class, CssClass);
            }
    }

    protected override void RenderContents(HtmlTextWriter writer) {
        if (HasControls()) {
            writer.RenderBeginTag(HtmlTextWriterTag.Ul);

            foreach (Control child in Controls) {
                var item = child as DataPagerFieldItem;
                if (item == null || !item.HasControls()) {
                    child.RenderControl(writer);
                    continue;
                }

                foreach (Control ctrl in item.Controls) {
                    var space = ctrl as LiteralControl;
                    if (space != null && space.Text == "&nbsp;")
                        continue;

                    // Set specific classes for li-Tag
                    bool isCurrentPage = false
                    if (ctrl is System.Web.UI.WebControls.WebControl) {
                        // Enabled = false -> "disabled"
                        if (!((System.Web.UI.WebControls.WebControl)ctrl).Enabled) {
                            writer.AddAttribute(HtmlTextWriterAttribute.Class, "disabled");
                        }

                        // there can only be one Label in the datapager -> "active"
                        if (ctrl is System.Web.UI.WebControls.Label) {
                           isCurrentPage = true;                     
                           writer.AddAttribute(HtmlTextWriterAttribute.Class, "active");
                        }
                    }
                    writer.RenderBeginTag(HtmlTextWriterTag.Li);
                    // special rendering as hyperlink for current page
                    if (isCurrentPage) {
                        writer.AddAttribute(HtmlTextWriterAttribute.Href, "#");
                        writer.RenderBeginTag(HtmlTextWriterTag.A);
                    }
                    ctrl.RenderControl(writer);
                    if (isCurrentPage) {
                        writer.RenderEndTag(); // A
                    }
                    writer.RenderEndTag();
                }
            }

            writer.RenderEndTag();
        }
   }
查看更多
登录 后发表回答