protected virtual string BeginForm <TModel>(HtmlHelper htmlHelper, RoboUIFormResult <TModel> roboForm, string formId) where TModel : class
        {
            if (roboForm.Layout == RoboUIFormLayout.Wizard)
            {
                roboForm.FormActionUrl = null;
            }

            string formActionUrl = string.IsNullOrEmpty(roboForm.FormActionUrl)
                ? htmlHelper.ViewContext.HttpContext.Request.RawUrl
                : roboForm.FormActionUrl;

            var form = new FluentTagBuilder("form", TagRenderMode.StartTag)
                       .MergeAttribute("action", formActionUrl)
                       .MergeAttribute("id", formId)
                       .MergeAttribute("method", roboForm.FormMethod.ToString().ToLowerInvariant());

            if (roboForm.Layout == RoboUIFormLayout.Tab)
            {
                form = form.MergeAttribute("data-ajax-begin", formId.Replace("-", "_") + "_ValidateTabs");
            }

            if (!roboForm.AjaxEnabled)
            {
                form = form.MergeAttribute("enctype", "multipart/form-data");
            }
            else
            {
                form = form.MergeAttribute("data-ajax", "true");
            }

            form = form.MergeAttribute("method", roboForm.FormMethod.ToString().ToLowerInvariant());
            form = form.MergeAttributes(roboForm.HtmlAttributes);

            return(form.ToString());
        }
        public virtual IHtmlContent Button(string text, State state, string onClick = null, object htmlAttributes = null)
        {
            string stateCss = GetButtonCssClass(state);

            var builder = new FluentTagBuilder("button")
                          .MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes))
                          .MergeAttribute("type", "button")
                          .AddCssClass(stateCss)
                          .SetInnerHtml(text);

            if (!string.IsNullOrEmpty(onClick))
            {
                builder.MergeAttribute("onclick", onClick);
            }

            return(new HtmlString(builder.ToString()));
        }
        protected virtual string BeginForm <TModel>(HtmlHelper htmlHelper, RoboUIGridResult <TModel> roboGrid) where TModel : class
        {
            if (string.IsNullOrEmpty(roboGrid.FormActionUrl))
            {
                return(string.Empty);
            }

            var form = new FluentTagBuilder("form", TagRenderMode.StartTag)
                       .MergeAttribute("action", roboGrid.FormActionUrl)
                       .MergeAttribute("method", "post");

            if (roboGrid.IsAjaxSupported)
            {
                form = form.MergeAttribute("data-ajax", "true");
            }

            return(form.ToString());
        }
        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);
            }
        }
    }
        /// <summary>
        /// Construct list selector according to parameters.
        /// </summary>
        /// <exception cref="ArgumentNullException">
        /// When expression or source is null.
        /// </exception>
        /// <typeparam name="TModel">Type of model.</typeparam>
        /// <typeparam name="TProperty">Type of property.</typeparam>
        /// <param name="htmlHelper">HtmlHelper.</param>
        /// <param name="expression">Expression to select needed property.</param>
        /// <param name="source">Source of list to select from.</param>
        /// <param name="enableMultiSelect">Enable selecting multiple items at once.</param>
        /// <param name="htmlAttributes">Html attributes.</param>
        /// <returns>Constructed list selector as FluentTagBuilder.</returns>
        internal static FluentTagBuilder ConstructListSelector <TModel, TProperty>(
            this HtmlHelper <TModel> htmlHelper,
            Expression <Func <TModel, TProperty> > expression,
            SelectList source,
            bool enableMultiSelect,
            object htmlAttributes)
        {
            if (expression == null)
            {
                throw new ArgumentNullException(nameof(expression));
            }

            if (source == null ||
                source.Items == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            // Determine main class
            string ulCssClass = enableMultiSelect
                ? "list-multi-selector-for"
                : "list-selector-for";
            string contentContainerCssClass = "content-container";
            string errorCssClass            = string.Format("{0}__error", ulCssClass);

            // Get model metadata
            ModelMetadata metadata = ModelMetadata
                                     .FromLambdaExpression(expression, htmlHelper.ViewData);

            // Declare model data and get it from metadata
            string        modelData     = null;
            List <string> listModelData = null;

            if (metadata.Model != null)
            {
                if (enableMultiSelect)
                {
                    listModelData = ((IEnumerable)metadata.Model)
                                    .Cast <object>()
                                    .Where(m => m != null)
                                    .Select(m => m.ToString())
                                    .ToList();
                }
                else
                {
                    modelData = metadata.Model.ToString();
                }
            }

            // Convert html attributes
            RouteValueDictionary attributes = HtmlHelper
                                              .AnonymousObjectToHtmlAttributes(htmlAttributes);

            // Construct ul tag.
            FluentTagBuilder ulBuilder = new FluentTagBuilder("ul")
                                         .MergeAttributes(attributes)
                                         .AddCssClass(ulCssClass);

            // Loop through items and add them to list
            foreach (SelectListItem listItem in source.Items)
            {
                // Initialize icon
                FluentTagBuilder icon = new FluentTagBuilder("i")
                                        .AddCssClass("default-icons")
                                        .SetInnerHtml("keyboard_arrow_right");

                // Initialize span
                FluentTagBuilder span = new FluentTagBuilder("span")
                                        .SetInnerHtml(listItem.Text);

                // Initialize hidden selector field to select.
                // If multiselect enabled, then this field should be
                // checkbox, otherwise it should be radio button.
                string hiddenSelector;
                if (enableMultiSelect)
                {
                    // Get model name form expression
                    string modelName = ExpressionHelper.GetExpressionText(expression);

                    // Get validation attributes
                    IDictionary <string, object> validationAttributes =
                        htmlHelper.GetUnobtrusiveValidationAttributes(modelName, metadata);

                    // Determine if list item is checked
                    bool isChecked = listModelData != null &&
                                     listModelData.Contains(listItem.Value);

                    FluentTagBuilder hiddenCheckBox = new FluentTagBuilder("input")
                                                      .MergeAttribute("name", modelName)
                                                      .MergeAttribute("id", modelName)
                                                      .MergeAttribute("value", listItem.Value)
                                                      .MergeAttribute("type", "checkbox")
                                                      .MergeAttribute("hidden", "hidden")
                                                      .MergeAttributes(validationAttributes);

                    if (isChecked)
                    {
                        hiddenCheckBox.MergeAttribute("checked", "true");
                    }

                    hiddenSelector = hiddenCheckBox.Render();
                }
                else
                {
                    hiddenSelector = htmlHelper
                                     .RadioButtonFor(expression, listItem.Value, new { hidden = "hidden" })
                                     .ToHtmlString();
                }

                // Initialize div and add elements inside.
                FluentTagBuilder containerDiv = new FluentTagBuilder("div")
                                                .AddCssClass(contentContainerCssClass)
                                                .AppendChild(icon)
                                                .AppendChild(span)
                                                .AppendChild(hiddenSelector);

                // Initialize li and set inner text
                FluentTagBuilder liBuilder = new FluentTagBuilder("li")
                                             .SetInnerHtml(containerDiv.Render());

                // Add li to listContentBuilder
                ulBuilder.AppendChild(liBuilder);
            }

            // Add error
            MvcHtmlString validationMessage = htmlHelper.ValidationMessageFor(expression);

            FluentTagBuilder errorSpan = new FluentTagBuilder("span")
                                         .AddCssClass(errorCssClass)
                                         .AppendChild(validationMessage);

            ulBuilder.AppendChild(errorSpan);

            return(ulBuilder);
        }
        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);
        }
Exemple #7
0
        /// <summary>
        /// Create combo date selector for date time.
        /// </summary>
        /// <exception cref="ArgumentNullException">
        /// When expression is null.
        /// </exception>
        /// <typeparam name="TModel">Type of model.</typeparam>
        /// <param name="htmlHelper">HtmlHelper.</param>
        /// <param name="expression">Property selector expression.</param>
        /// <param name="yearRange">Range of years.</param>
        /// <param name="htmlAttributes">Html attributes to add to combo date.</param>
        /// <returns>Combo date selector.</returns>
        public static MvcHtmlString ComboDateFor <TModel>(
            this HtmlHelper <TModel> htmlHelper,
            Expression <Func <TModel, DateTime> > expression,
            IEnumerable <int> yearRange,
            object htmlAttributes)

        {
            if (expression == null)
            {
                throw new ArgumentNullException(nameof(expression));
            }

            string comboDateCss      = "combo-date";
            string dayContainerCss   = "day-container";
            string monthContainerCss = "month-container";
            string yearContainerCss  = "year-container";
            string errorCss          = "combo-date__error";

            string dayText   = "Gün";
            string monthText = "Ay";
            string yearText  = "İl";

            // Initialize yearRange if has not been provided
            if (yearRange == null)
            {
                yearRange = Enumerable.Range(1900, 200);
            }

            // Get model metadata
            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(
                expression,
                htmlHelper.ViewData);

            string modelName = ExpressionHelper.GetExpressionText(expression);

            // Append HtmlFieldPrefix if there is any
            string fieldPrefix = htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix;

            if (!string.IsNullOrEmpty(fieldPrefix))
            {
                modelName = string.Format("{0}.{1}", fieldPrefix, modelName);
            }

            // Convert html attributes
            RouteValueDictionary attributes = HtmlHelper
                                              .AnonymousObjectToHtmlAttributes(htmlAttributes);

            // Initialize container div
            FluentTagBuilder comboDate = new FluentTagBuilder("div")
                                         .MergeAttributes(attributes)
                                         .AddCssClass(comboDateCss);

            // Initialize hidden text box for client side validation
            FluentTagBuilder input = new FluentTagBuilder("input")
                                     .MergeAttribute("name", modelName)
                                     .MergeAttribute("id", modelName)
                                     .MergeAttribute("type", "date")
                                     .MergeAttribute("hidden", "hidden")
                                     .MergeAttribute("readonly", "readonly");

            if (metadata.Model != null)
            {
                DateTime value = Convert.ToDateTime(metadata.Model);
                input.MergeAttribute("value", value.ToString("yyyy-MM-dd"));
            }

            //// Get validation attributes
            IDictionary <string, object> validationAttributes =
                htmlHelper.GetUnobtrusiveValidationAttributes(modelName, metadata);

            // Merge validation attributes
            input.MergeAttributes(validationAttributes);

            //contentBuilder.AppendLine(input.ToString());
            comboDate.AppendChild(input);

            // Declare date property selector
            Expression <Func <TModel, Int32> > datePropertySelector;

            // Select day property of date
            MemberExpression dayExpression = Expression.Property(expression.Body, "Day");

            datePropertySelector = Expression.Lambda <Func <TModel, Int32> >(
                dayExpression,
                expression.Parameters);

            // Create drop down button for day
            MvcHtmlString daySelector = htmlHelper
                                        .DropDownButtonFor <TModel, int>(
                datePropertySelector,
                new SelectList(Enumerable
                               .Range(1, 31)
                               .Select(m => new SelectListItem
            {
                Text  = m.ToString("00"),
                Value = m.ToString()
            })),
                dayText);

            // Setup day container
            FluentTagBuilder dayContainer = new FluentTagBuilder("div")
                                            .AddCssClass(dayContainerCss)
                                            .AppendChild(daySelector);

            //contentBuilder.AppendLine(dayContainer.ToString());

            comboDate.AppendChild(dayContainer);

            // Select month property of date
            MemberExpression monthExpression = Expression.Property(expression.Body, "Month");

            datePropertySelector = Expression.Lambda <Func <TModel, Int32> >(
                monthExpression,
                expression.Parameters);

            // Create drop down button for month
            MvcHtmlString monthSelector = htmlHelper
                                          .DropDownButtonFor <TModel, int>(
                datePropertySelector,
                new SelectList(Enumerable.Range(1, 12)
                               .Select(r => new SelectListItem
            {
                Value = r.ToString(),
                Text  = DateTimeFormatInfo.CurrentInfo.GetMonthName(r)
            })),
                monthText);

            // Setup month container
            FluentTagBuilder monthContainer = new FluentTagBuilder("div")
                                              .AddCssClass(monthContainerCss)
                                              .AppendChild(monthSelector);

            //contentBuilder.AppendLine(monthContainer.ToString());

            comboDate.AppendChild(monthContainer);

            // Select year property of date
            MemberExpression yearExpression = Expression.Property(expression.Body, "Year");

            datePropertySelector = Expression.Lambda <Func <TModel, Int32> >(
                yearExpression,
                expression.Parameters);

            // Create drop down button for month
            MvcHtmlString yearSelector = htmlHelper
                                         .DropDownButtonFor <TModel, int>(
                datePropertySelector,
                new SelectList(yearRange
                               .Select(r => new SelectListItem
            {
                Text  = r.ToString(),
                Value = r.ToString()
            })),
                yearText);

            // Setup year container
            FluentTagBuilder yearContainer = new FluentTagBuilder("div")
                                             .AddCssClass(yearContainerCss)
                                             .AppendChild(yearSelector);

            comboDate.AppendChild(yearContainer);

            // Set up error span
            MvcHtmlString validationMessage = htmlHelper
                                              .ValidationMessageFor(expression);

            FluentTagBuilder errorSpan = new FluentTagBuilder("span")
                                         .AddCssClass(errorCss)
                                         .AppendChild(validationMessage);

            comboDate.AppendChild(errorSpan);

            return(new MvcHtmlString(comboDate.Render()));
        }