I've got this MVC Pager Helper and it's working exactly as expected. I'm wondering if there's a prettier or more performant way to build this out?
Also, I know that the StringBuilder might not be the best way, would a TagBuilder be a better approach?
<Extension()>
Public Function Pager(helper As HtmlHelper,
urlPrefix As String,
totalRecords As Integer,
currentPage As Integer) As MvcHtmlString
' Get out if we have 5 or less records
If totalRecords <= 5 Then Return Nothing
' Make sure we're not getting invalid pages
If currentPage <= 0 Then currentPage = 1
' Setup our initial variables
Dim sb1 As New StringBuilder(),
totalPages = (Math.Round((totalRecords / 5) + 0.5)),
startingPoint,
linksAfterCurrent,
endPoint,
i
' Set boundries for inner link numbers
Select Case currentPage
Case totalPages : startingPoint = currentPage - 5
Case (totalPages - 1) : startingPoint = currentPage - 4
Case Else : startingPoint = currentPage - 3
End Select
Select Case currentPage
Case 1 : linksAfterCurrent = currentPage + 4
Case 2 : linksAfterCurrent = currentPage + 3
Case Else : linksAfterCurrent = currentPage + 2
End Select
sb1.Append("<div id=""pagercontainer""><ul class=""pager"">")
' Display the previous button and first button
If currentPage > 1 AndAlso startingPoint >= 1 Then
sb1.AppendLine([String].Format("<li><a href=""{0}1"" title=""go to page 1"">1</a></li>", urlPrefix))
sb1.AppendLine([String].Format("<li><a href=""{0}{1}"" title=""go to page {1}"">«</a></li>", urlPrefix, startingPoint))
sb1.AppendLine(" ")
End If
' Generate the inner numbers
i = startingPoint
While (i < linksAfterCurrent)
If (i >= 0) AndAlso
(i < totalPages) Then
sb1.AppendLine([String].Format("<li><a href=""{0}{1}"" {2} title=""go to page {1}"">{1}</a></li>",
urlPrefix,
i + 1,
If(i + 1 = currentPage, "class=""youarehere""", String.Empty)))
End If
i += 1
End While
endPoint = i
' Display the next button and the last button
If (currentPage < endPoint) AndAlso
(endPoint < totalPages) Then
sb1.AppendLine(" ")
sb1.AppendLine([String].Format("<li><a href=""{0}{1}"" title=""go to page {1}"">»</a></li>", urlPrefix, endPoint + 1))
sb1.AppendLine([String].Format("<li><a href=""{0}{1}"" title=""go to page {1}"">{1}</a></li>", urlPrefix, totalPages.ToString()))
End If
sb1.Append("</ul></div><div class=""clear""></div>")
Return MvcHtmlString.Create(sb1.ToString())
End Function
sb1.Append("</ul></div><div class=""clear""></div>")
Return MvcHtmlString.Create(sb1.ToString())
End Function