示例#1
0
        private IHtmlContent GenerateHomeLink()
        {
            TagBuilder homeLi = new TagBuilder("li");

            homeLi.Attributes.Add("class", "breadcrumb-item");

            TagBuilder homeHref    = null;
            string     homeTitle   = HomeTitle ?? "Home";
            object     routeValues = RouteValues ?? new { Area = HomeArea };

            if (string.IsNullOrEmpty(HomeAction))
            {
                homeHref = new TagBuilder("a");
                homeHref.Attributes.Add("href", "/");
                homeHref.InnerHtml.Append(homeTitle);
            }
            else
            {
                homeHref = _generator.GenerateActionLink(ViewContext, homeTitle, HomeAction, HomeController, null, null, null, routeValues, null);
            }

            homeLi.InnerHtml.AppendHtml(homeHref);


            return(homeLi);
        }
示例#2
0
        /// <inheritdoc />
        public HtmlString ActionLink(
            [NotNull] string linkText,
            string actionName,
            string controllerName,
            string protocol,
            string hostname,
            string fragment,
            object routeValues,
            object htmlAttributes)
        {
            var tagBuilder = _htmlGenerator.GenerateActionLink(
                linkText,
                actionName,
                controllerName,
                protocol,
                hostname,
                fragment,
                routeValues,
                htmlAttributes);

            if (tagBuilder == null)
            {
                return(HtmlString.Empty);
            }

            return(tagBuilder.ToHtmlString(TagRenderMode.Normal));
        }
    public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
    {
        if (output == null)
        {
            throw new ArgumentNullException(nameof(output));
        }

        if (Action == null)
        {
            throw new InvalidOperationException("Action must be specified");
        }

        if (LinkText == null)
        {
            LinkText = string.Empty;
        }

        if (IsActive)
        {
            output.Attributes.Merge("class", "active");
        }

        var routeValues = RouteValues.ToDictionary(
            kvp => kvp.Key,
            kvp => (object)kvp.Value,
            StringComparer.OrdinalIgnoreCase);

        var action = Action.Replace("-", string.Empty, StringComparison.OrdinalIgnoreCase);
        var anchor = _htmlGenerator.GenerateActionLink(ViewContext, LinkText, action, Controller, null, null, null, routeValues, new { @class = "nav-link px-3" });

        anchor.InnerHtml.AppendHtml(await output.GetChildContentAsync());
        output.Content.AppendHtml(anchor);
    }
示例#4
0
        /// <inheritdoc />
        public IHtmlContent ActionLink(
            string linkText,
            string actionName,
            string controllerName,
            string protocol,
            string hostname,
            string fragment,
            object routeValues,
            object htmlAttributes)
        {
            if (linkText == null)
            {
                throw new ArgumentNullException(nameof(linkText));
            }

            var tagBuilder = _htmlGenerator.GenerateActionLink(
                ViewContext,
                linkText,
                actionName,
                controllerName,
                protocol,
                hostname,
                fragment,
                routeValues,
                htmlAttributes);

            if (tagBuilder == null)
            {
                return(HtmlString.Empty);
            }

            return(tagBuilder);
        }
示例#5
0
        private string GeneratePageItem(int page, string className)
        {
            string pageNumber = page.ToString();

            TagBuilder anchor = Generator.GenerateActionLink(
                ViewContext,
                pageNumber,
                ActionName,
                ControllerName,
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            if (Visible)
            {
                var dataTableContext = (DataTableContext)context.Items[typeof(DataTableTagHelper)];
                if (dataTableContext.ActionDataSet == null)
                {
                    dataTableContext.ActionDataSet = new List <ActionData>();
                }

                if (string.IsNullOrEmpty(ActionUrl))
                {
                    RouteValueDictionary routeValues = null;
                    if (_routeValues != null && _routeValues.Count > 0)
                    {
                        routeValues = new RouteValueDictionary(_routeValues);
                    }

                    var tagBuilder = _htmlGenerator.GenerateActionLink(
                        ViewContext,
                        linkText: string.Empty,
                        actionName: Action,
                        protocol: null,
                        hostname: null,
                        fragment: null,
                        controllerName: Controller,
                        routeValues: routeValues,
                        htmlAttributes: null);

                    if (tagBuilder != null)
                    {
                        ActionUrl = tagBuilder.Attributes["href"];
                    }
                }

                var actionData = new ActionData
                {
                    ActionTitle = ActionTitle,
                    ActionUrl   = ActionUrl
                };
                if (!string.IsNullOrEmpty(CanExecutePropertyName))
                {
                    if (CanExecutePropertyName.Length >= 2)
                    {
                        actionData.CanExecutePropertyName = Char.ToLowerInvariant(CanExecutePropertyName[0]) + CanExecutePropertyName.Substring(1);
                    }
                    else
                    {
                        actionData.CanExecutePropertyName = CanExecutePropertyName.ToLower();
                    }
                }
                dataTableContext.ActionDataSet.Add(actionData);
                output.SuppressOutput();
            }
        }
示例#7
0
        private TagBuilder GenerateActionLink(RouteValueDictionary routeValues)
        {
            // Link for default culture needs to be generated by route name in order to not put culture into query string
            if (string.Equals(CultureName, CultureHelper.GetDefaultCultureCode(siteService.CurrentSite.SiteName), StringComparison.InvariantCultureIgnoreCase))
            {
                routeValues.Remove("culture");
                return(htmlGenerator.GenerateRouteLink(ViewContext, LinkText, Startup.DEFAULT_WITHOUT_LANGUAGE_PREFIX_ROUTE_NAME, null, null, null, routeValues, null));
            }

            // Ensure correct culture prefix
            routeValues["culture"] = CultureName;
            return(htmlGenerator.GenerateActionLink(ViewContext, LinkText, null, null, null, null, null, routeValues, null));
        }
        /// <summary>
        /// Asynchronously executes the <see cref="TagHelper"/> with the given context and output.
        /// </summary>
        /// <param name="context">Contains information associated with the current HTML tag.</param>
        /// <param name="output">A stateful HTML element used to generate an HTML tag.</param>
        public async override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            if (SortBy == null)
            {
                throw new InvalidOperationException($"A {nameof(SortBy)} expression must be provided.");
            }
            if (Options == null)
            {
                throw new InvalidOperationException($"The {nameof(ListOptions)} must be provided.");
            }
            var sortBy      = SortBy.Metadata.PropertyName.ToLowerInvariant();
            var sortings    = Options.GetSortings().ToDictionary(s => s.Path.ToLowerInvariant());
            var sortByClass = sortings.ContainsKey(sortBy) ? $"{AttributePrefix}-{sortings[sortBy].Direction.ToLower() }" : null;

            if (output.Attributes.TryGetAttribute("class", out var css))
            {
                var classesList = css.Value.ToString().Split(' ').Where(name => !name.StartsWith("sort-", StringComparison.Ordinal)).ToList();
                if (!classesList.Contains(SortableClassName))
                {
                    classesList.Insert(0, SortableClassName);
                }
                if (!string.IsNullOrEmpty(sortByClass))
                {
                    classesList.Add(sortByClass);
                }
                output.Attributes.SetAttribute("class", string.Join(" ", classesList));
            }
            else
            {
                output.Attributes.SetAttribute("class", $"{SortableClassName} {sortByClass}".TrimEnd());
            }
            var childContent = await output.GetChildContentAsync();

            if (childContent.IsEmptyOrWhiteSpace)
            {
                var values      = Options.ToDictionary(new { Sort = SortBy.Metadata.PropertyName }).AsRouteValues();
                var routeValues = new RouteValueDictionary();
                foreach (var item in values)
                {
                    routeValues.Add(item.Key, item.Value);
                }
                var container = new TagBuilder("div");
                var anchorTag = Generator.GenerateActionLink(ViewContext, string.Empty, null, null, null, null, null, routeValues, null);
                var spanTag   = new TagBuilder("span");
                spanTag.InnerHtml.Append(SortBy.Metadata.GetDisplayName());
                anchorTag.InnerHtml.AppendHtml(spanTag);
                container.InnerHtml.AppendHtml(anchorTag);
                output.Content.SetHtmlContent(container);
            }
        }
示例#9
0
        private IHtmlContent PageLink(bool enabled, string content, int page, string cssClass, string title = null)
        {
            var active = Options.Page == page;
            //if (!enabled)
            //    return HtmlString.Empty;
            var routeValues = Options.ToDictionary(new { Page = page }).AsRouteValues();
            var container   = new TagBuilder("li");

            container.AddCssClass("page-item");
            if (null != cssClass)
            {
                container.AddCssClass(cssClass);
            }
            if (null != title)
            {
                container.MergeAttribute("title", title);
            }

            var anchorTag = Generator.GenerateActionLink(ViewContext,
                                                         string.Empty, null, null, null, null, null,
                                                         routeValues.ToRouteValueDictionary(),
                                                         null);

            anchorTag.AddCssClass("page-link");
            if (active)
            {
                container.AddCssClass("active");
                anchorTag.MergeAttribute("href", "", true);
            }
            if (!enabled)
            {
                container.AddCssClass("disabled");
                anchorTag.MergeAttribute("href", "", true);
            }
            var spanTag = new TagBuilder("span");

            spanTag.InnerHtml.SetContent(content);
            anchorTag.InnerHtml.AppendHtml(spanTag);
            container.InnerHtml.AppendHtml(anchorTag);
            return(container);
        }
示例#10
0
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = "div";
        output.TagMode = TagMode.StartTagAndEndTag;
        var actionAnchor = _htmlGenerator.GenerateActionLink(
            ViewContext,
            linkText: "Home",
            actionName: "Index",
            controllerName: null,
            fragment: null,
            hostname: null,
            htmlAttributes: null,
            protocol: null,
            routeValues: null
            );
        var builder = new HtmlContentBuilder();

        builder.AppendHtml("Here's the link: ");
        builder.AppendHtml(actionAnchor);
        output.Content.SetHtmlContent(builder);
    }
示例#11
0
        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            using (var writer = new StringWriter())
            {
                if (SfaSortColumn.Equals(SfaTableSortColumn, StringComparison.InvariantCultureIgnoreCase))
                {
                    var sortDirectionClass = SfaSortDirection == SortOrder.Asc
                        ? "sorted-ascending"
                        : "sorted-descending";

                    var classes = output.Attributes.FirstOrDefault(a => a.Name == "class")?.Value.ToString();

                    output.Attributes.SetAttribute("class",
                                                   string.IsNullOrEmpty(classes)
                            ? $"{sortDirectionClass}"
                            : $"{sortDirectionClass} {classes}");
                }

                output.Attributes.Add(DataSortDirectionName, new HtmlString(ToogleSortDirection()));

                var content = (await output.GetChildContentAsync()).GetContent();

                var routeValues = _routeValues?.Count > 0 ? new RouteValueDictionary(_routeValues) : new RouteValueDictionary();
                routeValues["SortColumn"]    = SfaSortColumn;
                routeValues["SortDirection"] = ToogleSortDirection();

                var link = _generator.GenerateActionLink(ViewContext, content,
                                                         AspAction, AspController, AspProtocol, AspHost, AspFragment,
                                                         routeValues,
                                                         GetPassThroughAttributes(output));

                link.WriteTo(writer, NullHtmlEncoder.Default);

                output.TagName = null;
                output.TagMode = TagMode.StartTagAndEndTag;
                output.Content.Clear();
                output.PostContent.SetHtmlContent(writer.ToString());
            }
        }
示例#12
0
        private TagBuilder Anchor(string linkText, string page, bool disable = false, string style = "")
        {
            RouteValueDictionary routeValues = new RouteValueDictionary(_routeValues)
            {
                { "page", page }
            };

            var disabledStyle = disable ? "disabled " : "";

            return(htmlGenerator.GenerateActionLink(
                       ViewContext,
                       linkText: linkText,
                       actionName: Action,
                       controllerName: Controller,
                       fragment: null,
                       hostname: null,
                       htmlAttributes: new Dictionary <string, object> {
                { "class", $"{disabledStyle}{style}" }
            },
                       protocol: null,
                       routeValues: routeValues
                       ));
        }
        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            var urlHelper = _urlHelperFactory.GetUrlHelper(
                new ActionContext(_contextAccessor.HttpContext,
                                  new RouteData(),
                                  ViewContext.ActionDescriptor));

            var actionDescriptor = (ViewContext.ActionDescriptor as ControllerActionDescriptor);

            if (String.IsNullOrEmpty(Action))
            {
                Action = actionDescriptor.ActionName;
            }

            if (String.IsNullOrEmpty(Controller))
            {
                Controller = actionDescriptor.ControllerName;
            }

            if (!String.IsNullOrEmpty(Area))
            {
                RouteValues.Add("area", Area);
            }
            else
            {
                RouteValues.Add("area", "");
            }

            dynamic routeValues = new ExpandoObject();

            if (_routeValues != null && _routeValues.Count > 0)
            {
                foreach (var obj in _routeValues)
                {
                    ((System.Collections.Generic.IDictionary <string, object>)routeValues)[obj.Key] = obj.Value;
                }
            }

            dynamic fbValues = new ExpandoObject();

            if (_fbValues != null && _fbValues.Count > 0)
            {
                foreach (var obj in _fbValues)
                {
                    ((System.Collections.Generic.IDictionary <string, object>)fbValues)[$"fb-{obj.Key}"] = obj.Value;
                }
            }
            var color = String.Empty;

            if (!String.IsNullOrEmpty(Icon))
            {
                if (Icon.Contains(":"))
                {
                    var iconValues = Icon.Split(':');
                    Icon  = iconValues[0];
                    color = iconValues[1];
                }
            }

            var cssClass = Icon ?? String.Empty;

            if (cssClass.StartsWith("fa-"))
            {
                cssClass = $"fa {cssClass}";
            }

            var icon = new FluentTagBuilder("i")
                       .AddCssClass(cssClass);

            if (!String.IsNullOrEmpty(color))
            {
                icon.MergeAttribute("style", $"color:{color}");
            }

            var content = await output.GetChildContentAsync();

            var linkContent = content.GetContent();

            if (String.IsNullOrEmpty(linkContent))
            {
                linkContent = caption;
            }

            var link   = _generator.GenerateActionLink(ViewContext, linkContent, Action, Controller, string.Empty, string.Empty, string.Empty, routeValues, null);
            var href   = link.Attributes["href"];
            var anchor = new FluentTagBuilder("a")
                         .MergeAttribute("href", href)
                         .MergeAttributes(fbValues)
                         .AppendHtml(icon)
                         .Append(" ")
                         .Append(linkContent);

            if (IsFancybox)
            {
                anchor.AddCssClass("fancybox");
            }
            if (IsDeleteLink)
            {
                anchor.AddCssClass("remove-object");
            }

            var builder = new FluentTagBuilder("li")
                          .AppendHtml(anchor);

            output.TagName = "";

            output.Content.SetHtmlContent(builder);
        }
示例#14
0
 public TagBuilder GenerateActionLink(ViewContext viewContext, string linkText, string actionName, string controllerName, string protocol, string hostname, string fragment, object routeValues, object htmlAttributes)
 {
     return(_htmlGenerator.GenerateActionLink(viewContext, linkText, actionName, controllerName, protocol, hostname, fragment, routeValues, htmlAttributes));
 }
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            var urlHelper = UrlHelperFactory.GetUrlHelper(
                new ActionContext(ContextAccessor.HttpContext,
                                  new RouteData(),
                                  new Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor()));

            var itemsPerPage = (ItemsPerPage ?? 0);

            if (itemsPerPage == 0)
            {
                int.TryParse(ViewOptions.PerPageDefault, out itemsPerPage);
            }

            var currentPage = (CurrentPage ?? 1);

            var totalItems = (TotalItems ?? 0);

            if (totalItems > itemsPerPage)
            {
                var totalPages = (totalItems + (itemsPerPage - 1)) / itemsPerPage;

                string controller  = String.IsNullOrEmpty(Controller) ? (ViewContext.ActionDescriptor as ControllerActionDescriptor)?.ControllerName : Controller;
                string action      = String.IsNullOrEmpty(Action) ? "Index" : Action;
                var    httpContext = ContextAccessor.HttpContext;

                var pageList = new List <string> {
                    "«",
                    "‹"
                };

                switch (totalPages)
                {
                case 2:
                    pageList.Add("1");
                    pageList.Add("2");
                    break;

                case 3:
                case 4:
                case 5:
                    for (var i = 1; i < totalPages; i++)
                    {
                        pageList.Add(i.ToString());
                    }
                    break;

                default:
                    if (currentPage < 4)
                    {
                        for (var i = 1; i < 6; i++)
                        {
                            pageList.Add(i.ToString());
                        }
                    }
                    else
                    {
                        var endPage = currentPage + 2 < totalPages ? currentPage + 3 : totalPages + 1;
                        for (var i = endPage - 5; i < endPage; i++)
                        {
                            pageList.Add(i.ToString());
                        }
                    }
                    break;
                }

                pageList.Add("›");
                pageList.Add("»");

                var list = new FluentTagBuilder("ul").AddCssClass("pagination pagination-sm")
                           .MergeAttribute("style", "display:inline;");

                dynamic routeValues = new ExpandoObject();
                foreach (var page in pageList)
                {
                    routeValues = new ExpandoObject();

                    if (page.IsNumeric())
                    {
                        routeValues = new { page, itemsPerPage }
                    }
                    ;
                    else if (page == "«")
                    {
                        routeValues = new { page = 1, itemsPerPage }
                    }
                    ;
                    else if (page == "‹")
                    {
                        routeValues = new {
                            page = currentPage - 1 > 0 ? currentPage - 1 : 1,
                            itemsPerPage
                        }
                    }
                    ;
                    else if (page == "›")
                    {
                        routeValues = new {
                            page = currentPage + 1 <= totalPages ? currentPage + 1 : totalPages,
                            itemsPerPage
                        }
                    }
                    ;
                    else if (page == "»")
                    {
                        routeValues = new {
                            page = totalPages,
                            itemsPerPage
                        }
                    }
                    ;
                    foreach (var obj in httpContext.Request.Query)
                    {
                        if (!obj.Key.Equals("page", StringComparison.CurrentCultureIgnoreCase))
                        {
                            routeValues[obj.Key] = obj.Value;
                        }
                    }

                    var li = new FluentTagBuilder("li")
                             .AppendHtml(Generator.GenerateActionLink(ViewContext, page, action, controller, string.Empty, string.Empty, string.Empty, routeValues, null));

                    if (page.IsNumeric())
                    {
                        if (Convert.ToInt32(page) == currentPage)
                        {
                            li.AddCssClass("active");
                        }
                    }
                    list.AppendHtml(li);
                }

                routeValues = new ExpandoObject();
                foreach (var obj in httpContext.Request.Query)
                {
                    if (!obj.Key.Equals("page", StringComparison.CurrentCultureIgnoreCase))
                    {
                        routeValues[obj.Key] = obj.Value;
                    }
                }

                var perPageSelect = new FluentTagBuilder("select")
                                    .GenerateId("ddlResultsPerPage", "")
                                    .MergeAttribute("style", "width:auto;float:left;margin-right:15px;")
                                    .MergeAttribute("data-url", urlHelper.Action(Action, Controller, (object)routeValues))
                                    .AddCssClass("itemCountDropdown form-control")
                                    .MergeAttribute("onchange", "javascript:window.location.href = $('.itemCountDropdown option:selected').attr('tag')");

                routeValues.Page = 1;

                foreach (var item in ViewOptions.PerPageList)
                {
                    routeValues.itemsPerPage = item.Value;
                    item.Selected            = item.Value == itemsPerPage.ToString();
                    var option = new FluentTagBuilder("option")
                                 .MergeAttribute("value", item.Value)
                                 .Append(item.Text)
                                 .MergeAttribute("tag", urlHelper.Action(action, controller, (object)routeValues));

                    if (item.Selected)
                    {
                        option.MergeAttribute("selected", "selected");
                    }

                    perPageSelect.AppendHtml(option);
                }

                output.PostElement.AppendHtml(perPageSelect);
                output.PostElement.AppendHtml(list);
            }
        }
    }
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            if (PagerContext == null)
            {
                return;
            }
            if (String.IsNullOrEmpty(ControllerName) || String.IsNullOrEmpty(ActionName))
            {
                throw new Exception("controllerName and actionName must be specified for PageLinks.");
            }
            if (PagerContext.PageCount <= 1)
            {
                return;
            }

            var builder = new StringBuilder();

            if (String.IsNullOrEmpty(MoreTextClass))
            {
                builder.Append($"<li><span>{Resources.More}:</span></li>");
            }
            else
            {
                builder.Append($"<li class=\"{MoreTextClass}\"><span>{Resources.More}</span></li>");
            }

            if (PagerContext.PageIndex != 1 && Low != 1)
            {
                // first page link
                builder.Append("<li>");
                var firstRouteDictionary = new RouteValueDictionary(new { controller = ControllerName, action = ActionName, page = 1 });
                if (RouteParameters != null)
                {
                    foreach (var item in RouteParameters)
                    {
                        firstRouteDictionary.Add(item.Key, item.Value);
                    }
                }
                var firstLink = _htmlGenerator.GenerateActionLink(ViewContext, "", ActionName, ControllerName, null, null, null,
                                                                  firstRouteDictionary, new { title = Resources.First, @class = "glyphicon glyphicon-step-backward" });
                builder.Append(GetString(firstLink));
                builder.Append("</li>");
                if (PagerContext.PageIndex > 2)
                {
                    // previous page link
                    var previousIndex = PagerContext.PageIndex - 1;
                    if (Low != 0)
                    {
                        previousIndex = Low - 1;
                    }
                    builder.Append("<li>");
                    var previousRouteDictionary = new RouteValueDictionary(new { controller = ControllerName, action = ActionName, page = previousIndex });
                    if (RouteParameters != null)
                    {
                        foreach (var item in RouteParameters)
                        {
                            previousRouteDictionary.Add(item.Key, item.Value);
                        }
                    }
                    var previousLink = _htmlGenerator.GenerateActionLink(ViewContext, "", ActionName, ControllerName, null, null, null, previousRouteDictionary, new { title = Resources.Previous, @class = "glyphicon glyphicon-chevron-left", rel = "prev" });
                    builder.Append(GetString(previousLink));
                    builder.Append("</li>");
                }
            }

            if (Low == 0 || High == 0)
            {
                // not a multipage set of links used in partial page
                // calc low and high limits for numeric links
                var low  = PagerContext.PageIndex - 1;
                var high = PagerContext.PageIndex + 3;
                if (low < 1)
                {
                    low = 1;
                }
                if (high > PagerContext.PageCount)
                {
                    high = PagerContext.PageCount;
                }
                if (high - low < 5)
                {
                    while ((high < low + 4) && high < PagerContext.PageCount)
                    {
                        high++;
                    }
                }
                if (high - low < 5)
                {
                    while ((low > high - 4) && low > 1)
                    {
                        low--;
                    }
                }
                for (var x = low; x < high + 1; x++)
                {
                    // numeric links
                    if (x == PagerContext.PageIndex)
                    {
                        if (String.IsNullOrEmpty(CurrentTextClass))
                        {
                            builder.Append(String.Format("<li><span class=\"active\">{0} of {1}</span></li>", x, PagerContext.PageCount));
                        }
                        else
                        {
                            builder.Append(String.Format("<li class=\"active {0}\"><span>{1} of {2}</span></li>", CurrentTextClass, x, PagerContext.PageCount));
                        }
                    }
                    else
                    {
                        builder.Append("<li>");
                        var numericRouteDictionary = new RouteValueDictionary {
                            { "controller", ControllerName }, { "action", ActionName }, { "page", x }
                        };
                        if (RouteParameters != null)
                        {
                            foreach (var item in RouteParameters)
                            {
                                numericRouteDictionary.Add(item.Key, item.Value);
                            }
                        }
                        var link = _htmlGenerator.GenerateActionLink(ViewContext, x.ToString(), ActionName, ControllerName, null, null, null, numericRouteDictionary, null);
                        builder.Append(GetString(link));
                        builder.Append("</li>");
                    }
                }
            }
            else
            {
                // multipage set of links used in partial page
                // calc low and high limits for numeric links
                var calcLow  = PagerContext.PageIndex - 1;
                var calcHigh = PagerContext.PageIndex + 3;
                if (calcLow < 1)
                {
                    calcLow = 1;
                }
                if (calcHigh > PagerContext.PageCount)
                {
                    calcHigh = PagerContext.PageCount;
                }
                if (calcHigh - calcLow < 5)
                {
                    while ((calcHigh < calcLow + 4) && calcHigh < PagerContext.PageCount)
                    {
                        calcHigh++;
                    }
                }
                if (calcHigh - calcLow < 5)
                {
                    while ((calcLow > calcHigh - 4) && calcLow > 1)
                    {
                        calcLow--;
                    }
                }
                var isRangeRendered = false;
                for (var x = calcLow; x < calcHigh + 1; x++)
                {
                    // numeric links
                    if (x >= Low && x <= High)
                    {
                        if (!isRangeRendered)
                        {
                            isRangeRendered = true;
                            if (String.IsNullOrEmpty(CurrentTextClass))
                            {
                                builder.Append(String.Format("<li class=\"active\"><span>{0}-{1} of {2}</span></li>", Low, High, PagerContext.PageCount));
                            }
                            else
                            {
                                builder.Append(String.Format("<li class=\"active {0}\"><span>{1}-{2} of {3}</span></li>", CurrentTextClass, Low, High, PagerContext.PageCount));
                            }
                        }
                    }
                    else
                    {
                        builder.Append("<li>");
                        var numericRouteDictionary = new RouteValueDictionary {
                            { "controller", ControllerName }, { "action", ActionName }, { "page", x }
                        };
                        if (RouteParameters != null)
                        {
                            foreach (var item in RouteParameters)
                            {
                                numericRouteDictionary.Add(item.Key, item.Value);
                            }
                        }
                        var link = _htmlGenerator.GenerateActionLink(ViewContext, x.ToString(), ActionName, ControllerName, null, null, null, numericRouteDictionary, null);
                        builder.Append(GetString(link));
                        builder.Append("</li>");
                    }
                }
            }

            if (PagerContext.PageIndex != PagerContext.PageCount && High < PagerContext.PageCount)
            {
                if (PagerContext.PageIndex < PagerContext.PageCount - 1)
                {
                    // next page link
                    var nextIndex = PagerContext.PageIndex + 1;
                    builder.Append("<li>");
                    var nextRouteDictionary = new RouteValueDictionary(new { controller = ControllerName, action = ActionName, page = nextIndex });
                    if (RouteParameters != null)
                    {
                        foreach (var item in RouteParameters)
                        {
                            nextRouteDictionary.Add(item.Key, item.Value);
                        }
                    }
                    var nextLink = _htmlGenerator.GenerateActionLink(ViewContext, "", ActionName, ControllerName, null, null, null, nextRouteDictionary, new { title = Resources.Next, @class = "glyphicon glyphicon-chevron-right", rel = "next" });
                    builder.Append(GetString(nextLink));
                    builder.Append("</li>");
                }
                // last page link
                builder.Append("<li>");
                var lastRouteDictionary = new RouteValueDictionary(new { controller = ControllerName, action = ActionName, page = PagerContext.PageCount });
                if (RouteParameters != null)
                {
                    foreach (var item in RouteParameters)
                    {
                        lastRouteDictionary.Add(item.Key, item.Value);
                    }
                }
                var lastLink = _htmlGenerator.GenerateActionLink(ViewContext, "", ActionName, ControllerName, null, null, null, lastRouteDictionary, new { title = Resources.Last, @class = "glyphicon glyphicon-step-forward", rel = "next" });
                builder.Append(GetString(lastLink));
                builder.Append("</li>");
            }

            output.TagMode = TagMode.StartTagAndEndTag;
            output.TagName = "ul";
            if (!String.IsNullOrWhiteSpace(Class))
            {
                output.Attributes.Add("class", Class);
            }
            output.Content.AppendHtml(builder.ToString());
        }
示例#17
0
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            var modelMetadata = ViewContext.ViewData.ModelMetadata;

            var props = new List <ModelMetadata>();            //			GetProperties(modelMetadata);

            props.AddRange(MetadataProvider.GetMetadataForProperties(modelMetadata.ElementType ?? modelMetadata.ModelType));

            var columnName = string.Empty;

            if (!DisplayFor.Contains("."))
            {
                var chosen = props.SingleOrDefault(p => p.PropertyName == DisplayFor);
                if (chosen != null)
                {
                    output.Content.SetContent(chosen.GetDisplayName());
                    columnName = chosen.PropertyName;
                }
            }
            else
            {
                var propertyNames = DisplayFor.Split('.');
                foreach (var propertyName in propertyNames)
                {
                    modelMetadata = props.SingleOrDefault(p => p.PropertyName == propertyName);
                    if (modelMetadata == null)
                    {
                        break;
                    }
                    if (propertyName == propertyNames[propertyNames.Length - 1])
                    {
                        var displayName = modelMetadata.GetDisplayName();
                        if (String.IsNullOrEmpty(displayName))
                        {
                            displayName = propertyName;
                        }
                        output.Content.SetContent(displayName);
                        columnName = modelMetadata.PropertyName;
                    }
                    else
                    {
                        props.Clear();
                        props.AddRange(MetadataProvider.GetMetadataForProperties(modelMetadata.ElementType));
                    }
                }
            }

            if (Sort)
            {
                var urlHelper = UrlHelperFactory.GetUrlHelper(new ActionContext(ContextAccessor.HttpContext, new Microsoft.AspNetCore.Routing.RouteData(), new Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor()));                 //ContextAccessor.HttpContext.RequestServices.GetRequiredService<IUrlHelper>();

                var itemsPerPage = 0;
                int.TryParse(ContextAccessor.HttpContext.Request.Query["itemsPerPage"], out itemsPerPage);

                if (itemsPerPage == 0)
                {
                    int.TryParse(ViewOptions.PerPageDefault, out itemsPerPage);
                }

                var currentPage = 1;
                int.TryParse(ContextAccessor.HttpContext.Request.Query["page"], out currentPage);
                if (currentPage == 0)
                {
                    currentPage = 1;
                }

                var controller = String.IsNullOrEmpty(Controller) ? (ViewContext.ActionDescriptor as ControllerActionDescriptor)?.ControllerName : Controller;

                var action = String.IsNullOrEmpty(Action) ? ViewContext.RouteData.Values["action"].ToString() : Action;
                if (string.IsNullOrEmpty(action))
                {
                    action = "Index";
                }

                dynamic routeValues = new ExpandoObject();
                foreach (var obj in ContextAccessor.HttpContext.Request.Query)
                {
                    ((System.Collections.Generic.IDictionary <string, object>)routeValues)[obj.Key] = obj.Value;
                }

                routeValues.sortColumn = columnName;
                routeValues.sortOrder  = SortOrder.Ascending;

                var ul = new FluentTagBuilder("ul")
                         .AddCssClass("sort-spinner")
                         .AppendHtml(new FluentTagBuilder("li")
                                     .AppendHtml(Generator.GenerateActionLink(ViewContext,
                                                                              string.Empty,
                                                                              action,
                                                                              controller,
                                                                              string.Empty,
                                                                              string.Empty,
                                                                              string.Empty,
                                                                              routeValues,
                                                                              new { @class = "fa fa-sort-asc" })));
                routeValues.sortOrder = SortOrder.Descending;
                ul.AppendHtml(new FluentTagBuilder("li")
                              .AppendHtml(Generator.GenerateActionLink(ViewContext,
                                                                       string.Empty,
                                                                       action,
                                                                       controller,
                                                                       string.Empty,
                                                                       string.Empty,
                                                                       string.Empty,
                                                                       routeValues,
                                                                       new { @class = "fa fa-sort-desc" })));

                output.Content.AppendHtml(ul);
            }
        }