/// <summary>
        ///
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="metadata"></param>
        /// <param name="fieldName"></param>
        /// <param name="minDate"></param>
        /// <param name="maxDate"></param>
        private static string DatePickerForHelper(System.Web.Mvc.HtmlHelper helper, ModelMetadata metadata,
                                                  string fieldName, DateTime?minDate = null, DateTime?maxDate = null)
        {
            // Validate the model type is DateTime or Nullable<DateTime>
            if (!(metadata.Model is DateTime || Nullable.GetUnderlyingType(metadata.ModelType) == typeof(DateTime)))
            {
                throw new ArgumentException(string.Format(_NotADate, fieldName));
            }
            //  Validate dates
            if (minDate.HasValue && maxDate.HasValue && minDate.Value >= maxDate.Value)
            {
                throw new ArgumentException("The minimum date cannot be greater than the maximum date");
            }
            if (minDate.HasValue && metadata.Model != null && (DateTime)metadata.Model < minDate.Value)
            {
                throw new ArgumentException("The date cannot be less than the miniumum date");
            }
            if (maxDate.HasValue && metadata.Model != null && (DateTime)metadata.Model > maxDate.Value)
            {
                throw new ArgumentException("The date cannot be greater than the maximum date");
            }
            //  Construct date picker
            StringBuilder html = new StringBuilder();

            // Add display text
            html.Append(DatePickerText(metadata));
            // Add input
            html.Append(DatePickerInput(helper, metadata, fieldName));
            // Add drop button
            html.Append(ButtonHelper.DropButton());
            // Get the default date to display
            DateTime date       = DateTime.Today;
            bool     isSelected = false;

            // If a date has been provided, use it and mark it as selected
            if (metadata.Model != null)
            {
                date       = (DateTime)metadata.Model;
                isSelected = true;
            }
            // Add calendar
            html.Append(Calendar(date, isSelected, minDate, maxDate));
            // Build container
            System.Web.Mvc.TagBuilder container = new System.Web.Mvc.TagBuilder("div");
            container.AddCssClass("datepicker-container");
            // Add min and max date attributes
            if (minDate.HasValue)
            {
                container.MergeAttribute("data-mindate", string.Format("{0:d/M/yyyy}", minDate.Value));
            }
            if (maxDate.HasValue)
            {
                container.MergeAttribute("data-maxdate", string.Format("{0:d/M/yyyy}", maxDate.Value));
            }
            container.InnerHtml = html.ToString();
            // Return the html
            return(container.ToString());;
        }
    private static string CreateTableString(string header, string body, GenericTableVModel model)
    {
        StringBuilder html = new StringBuilder();

        System.Web.Mvc.TagBuilder table = new System.Web.Mvc.TagBuilder("table");
        table.MergeAttribute("class", model.Setting.Class);
        table.MergeAttribute("id", model.Setting.Id);

        table.InnerHtml = header + body;

        html.Append(table.ToString());

        return(html.ToString());
    }
 /// <summary>
 /// Returns the html for a table cell with a navigation button.
 /// </summary>
 /// <param name="className">
 /// The class name to apply to the button.
 /// </param>
 /// <param name="hide">
 /// A value indicating if the button should be rendered as hidden.
 /// </param>
 private static string NavigationButton(string className, bool hide)
 {
     // Build the button
     System.Web.Mvc.TagBuilder button = new System.Web.Mvc.TagBuilder("button");
     button.AddCssClass(className);
     button.MergeAttribute("type", "button");
     button.MergeAttribute("tabindex", "-1");
     if (hide)
     {
         button.MergeAttribute("style", "display:none;");
     }
     // Construct the table cell
     System.Web.Mvc.TagBuilder cell = new System.Web.Mvc.TagBuilder("th");
     cell.InnerHtml = button.ToString();
     // Return the html
     return(cell.ToString());
 }
 /// <summary>
 /// Returns the html for the date picker input, including validation attributes and message.
 /// </summary>
 /// <param name="helper">
 /// The html helper.
 /// </param>
 /// <param name="metadata">
 /// The meta data of the property to display the date for.
 /// </param>
 /// <param name="name">
 /// The fully qualified name of the property.
 /// </param>
 /// <returns></returns>
 private static string DatePickerInput(System.Web.Mvc.HtmlHelper helper, System.Web.Mvc.ModelMetadata metadata, string name)
 {
     // Construct the input
     System.Web.Mvc.TagBuilder input = new System.Web.Mvc.TagBuilder("input");
     input.AddCssClass("datepicker-input");
     input.MergeAttribute("type", "text");
     input.MergeAttribute("id", System.Web.Mvc.HtmlHelper.GenerateIdFromName(name));
     input.MergeAttribute("autocomplete", "off");
     input.MergeAttribute("name", name);
     input.MergeAttributes(helper.GetUnobtrusiveValidationAttributes(name, metadata));
     if (metadata.Model != null)
     {
         input.MergeAttribute("value", ((DateTime)metadata.Model).ToShortDateString());
     }
     // Return the html
     return(input.ToString());
 }
    private static string TableCellCheckBox(ModelMetadata metaData, string fieldName)
    {
        StringBuilder html = new StringBuilder();

        // Checkbox
        System.Web.Mvc.TagBuilder checkbox = new System.Web.Mvc.TagBuilder("input");
        checkbox.MergeAttribute("type", "checkbox");
        checkbox.MergeAttribute("name", fieldName);
        checkbox.MergeAttribute("id", fieldName);
        //checkbox.MergeAttribute("value", "true");
        checkbox.MergeAttribute("disabled", "disabled");
        checkbox.MergeAttribute("class", "checkbox");
        if (metaData.Model != null && (bool)metaData.Model)
        {
            checkbox.MergeAttribute("checked", "checked");
        }
        html.Append(checkbox.ToString(TagRenderMode.SelfClosing));
        // Build additional hidden input to address scenario where
        // unchecked checkboxes are not sent in the request.

        //System.Web.Mvc.TagBuilder hidden = new System.Web.Mvc.TagBuilder("input");
        //hidden.MergeAttribute("type", "hidden");
        //hidden.MergeAttribute("name", fieldName);
        //checkbox.MergeAttribute("id", fieldName);
        //hidden.MergeAttribute("value", "false");
        //html.Append(hidden.ToString(TagRenderMode.SelfClosing));

        // Table cell

        return(html.ToString());
    }
 /// <summary>
 /// Returns the html for the date picker display text (visible when the datepicker does not have focus)
 /// </summary>
 /// <param name="metadata">
 /// The meta data of the property to display the date for.
 /// </param>
 private static string DatePickerText(ModelMetadata metadata)
 {
     System.Web.Mvc.TagBuilder text = new System.Web.Mvc.TagBuilder("div");
     text.AddCssClass("datepicker-text");
     // Add essential stype properties
     text.MergeAttribute("style", "position:absolute;z-index:-1000;");
     if (metadata.Model != null)
     {
         text.InnerHtml = ((DateTime)metadata.Model).ToLongDateString();
     }
     // Return the html
     return(text.ToString());
 }
        /// <summary>
        /// Returns the html for the table header row displaying the current month and navigation buttons.
        /// </summary>
        /// <param name="date">
        /// A date in the month to display.
        /// </param>
        /// <param name="minDate">
        /// The minimum date that can be selected.
        /// </param>
        /// <param name="maxDate">
        /// The maximmum date that can be selected.
        /// </param>
        private static string MonthHeader(DateTime date, DateTime?minDate, DateTime?maxDate)
        {
            StringBuilder html = new StringBuilder();
            // Add previous month navigation button
            bool hidePrevious = minDate.HasValue && date.FirstOfMonth() <= minDate.Value;

            html.Append(NavigationButton("previousButton", hidePrevious));
            // Add month label
            System.Web.Mvc.TagBuilder label = new System.Web.Mvc.TagBuilder("span");
            label.InnerHtml = string.Format("{0:MMMM yyyy}", date);
            System.Web.Mvc.TagBuilder cell = new System.Web.Mvc.TagBuilder("th");
            cell.MergeAttribute("colspan", "5");
            cell.InnerHtml = label.ToString();
            html.Append(cell);
            // Add next month navigation button
            bool hideNext = maxDate.HasValue && date.LastOfMonth() >= maxDate.Value;

            html.Append(NavigationButton("nextButton", hideNext));
            // Construct header row
            System.Web.Mvc.TagBuilder header = new System.Web.Mvc.TagBuilder("tr");
            header.InnerHtml = html.ToString();
            // Return the html
            return(header.ToString());
        }
Beispiel #8
0
        /// <summary>
        /// Creates an an individual checkbox
        /// </summary>
        /// <param name="sb">String builder of checkbox list</param>
        /// <param name="modelMetadata">Model Metadata</param>
        /// <param name="htmlWrapper">MVC Html helper class that is being extended</param>
        /// <param name="htmlAttributesForCheckBox">Each checkbox HTML tag attributes (e.g. 'new { class="somename" }')</param>
        /// <param name="selectedValues">List of strings of selected values</param>
        /// <param name="disabledValues">List of strings of disabled values</param>
        /// <param name="name">Name of the checkbox list (same for all checkboxes)</param>
        /// <param name="itemValue">Value of the checkbox</param>
        /// <param name="itemText">Text to be displayed next to checkbox</param>
        /// <param name="htmlHelper">HtmlHelper passed from view model</param>
        /// <param name="textLayout">Sets layout of a checkbox for right-to-left languages</param>
        /// <returns>String builder of checkbox list</returns>
        private static StringBuilder CreateCheckBoxListElement(StringBuilder sb, HtmlHelper htmlHelper, ModelMetadata modelMetadata, HtmlWrapperInfo htmlWrapper, object htmlAttributesForCheckBox, IEnumerable <string> selectedValues, IEnumerable <string> disabledValues, string name, string itemValue, string itemText, TextLayout textLayout)
        {
            // get full name from view model
            var fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);

            // create checkbox tag
            var checkbox_builder = new TagBuilder("input");

            if (selectedValues.Any(x => x == itemValue))
            {
                checkbox_builder.MergeAttribute("checked", "checked");
            }
            checkbox_builder.MergeAttributes(htmlAttributesForCheckBox.ToDictionary());
            checkbox_builder.MergeAttribute("type", "checkbox");
            checkbox_builder.MergeAttribute("value", itemValue);
            checkbox_builder.MergeAttribute("name", fullName);

            // create linked label tag
            var link_name = name + linkedLabelCount++;

            checkbox_builder.GenerateId(link_name);
            var linked_label_builder = new TagBuilder("label");

            linked_label_builder.MergeAttribute("for", link_name.Replace(".", "_"));
            linked_label_builder.MergeAttributes(htmlAttributesForCheckBox.ToDictionary());
            linked_label_builder.InnerHtml = itemText;

            // if there are any errors for a named field, we add the css attribute
            ModelState modelState;

            if (htmlHelper.ViewData.ModelState.TryGetValue(fullName, out modelState))
            {
                if (modelState.Errors.Count > 0)
                {
                    checkbox_builder.AddCssClass(HtmlHelper.ValidationInputCssClassName);
                }
            }
            checkbox_builder.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(name, modelMetadata));

            // open checkbox tag wrapper
            if (textLayout == TextLayout.RightToLeft)
            {
                // then set style for displaying checkbox for right-to-left languages
                var defaultSectionStyle = "style=\"text-align: right;\"";
                sb.Append(htmlWrapper.WrapElement != HtmlElementTag.None
                            ? "<" + htmlWrapper.WrapElement + " " + defaultSectionStyle + ">"
                            : "");
            }
            else
            {
                sb.Append(htmlWrapper.WrapElement != HtmlElementTag.None
                            ? "<" + htmlWrapper.WrapElement + ">"
                            : "");
            }

            // build hidden tag for disabled checkbox (so the value will post)
            if (disabledValues != null && disabledValues.ToList().Any(x => x == itemValue))
            {
                // set main checkbox to be disabled
                checkbox_builder.MergeAttribute("disabled", "disabled");

                // create a hidden input with checkbox value
                // so it can be posted if checked
                if (selectedValues.Any(x => x == itemValue))
                {
                    var hidden_input_builder = new TagBuilder("input");
                    hidden_input_builder.MergeAttribute("type", "hidden");
                    hidden_input_builder.MergeAttribute("value", itemValue);
                    hidden_input_builder.MergeAttribute("name", name);
                    sb.Append(hidden_input_builder.ToString(TagRenderMode.Normal));
                }
            }

            // create checkbox and tag combination
            if (textLayout == TextLayout.RightToLeft)
            {
                // then display checkbox for right-to-left languages
                sb.Append(linked_label_builder.ToString(TagRenderMode.Normal));
                sb.Append(checkbox_builder.ToString(TagRenderMode.Normal));
            }
            else
            {
                sb.Append(checkbox_builder.ToString(TagRenderMode.Normal));
                sb.Append(linked_label_builder.ToString(TagRenderMode.Normal));
            }

            // close checkbox tag wrapper
            sb.Append(htmlWrapper.WrapElement != HtmlElementTag.None
                        ? "</" + htmlWrapper.WrapElement + ">"
                        : "");

            // add element ending
            sb.Append(htmlWrapper.AppendToElement);

            // add table column break, if applicable
            htmlwrapRowbreakCount += 1;
            if (htmlwrapRowbreakCount == htmlWrapper.SeparatorMaxCount)
            {
                sb.Append(htmlWrapper.WrapRowbreak);
                htmlwrapRowbreakCount = 0;
            }

            // return string builder with checkbox html markup
            return(sb);
        }
Beispiel #9
0
        /// <summary>
        /// Creates an HTML wrapper for the checkbox list
        /// </summary>
        /// <param name="htmlListInfo">Settings for HTML wrapper of the list (e.g. 'new HtmlListInfo2(HtmlTag2.vertical_columns, 2, new { style="color:green;" })')</param>
        /// <param name="numberOfItems">Count of all items in the list</param>
        /// <param name="position">Direction of the list (e.g. 'Position2.Horizontal' or 'Position2.Vertical')</param>
        /// <param name="textLayout">Sets layout of a checkbox for right-to-left languages</param>
        /// <returns>HTML wrapper information</returns>
        private static HtmlWrapperInfo CreateHtmlWrapper(HtmlListInfo htmlListInfo, int numberOfItems, Position position, TextLayout textLayout)
        {
            var htmlWrapInfo = new HtmlWrapperInfo();

            if (htmlListInfo != null)
            {
                // creating custom layouts
                switch (htmlListInfo.HtmlTag)
                {
                // creates user selected number of float sections with
                // vertically sorted checkboxes
                case HtmlTag.VerticalColumns:
                {
                    if (htmlListInfo.Columns <= 0)
                    {
                        htmlListInfo.Columns = 1;
                    }
                    // calculate number of rows
                    var rows = Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(numberOfItems)
                                                            / Convert.ToDecimal(htmlListInfo.Columns)));
                    if (numberOfItems <= 4 &&
                        (numberOfItems <= htmlListInfo.Columns || numberOfItems - htmlListInfo.Columns == 1))
                    {
                        rows = numberOfItems;
                    }
                    htmlWrapInfo.SeparatorMaxCount = rows;

                    // create wrapped raw html tag
                    var wrapRow              = HtmlElementTag.Div;
                    var wrapHtml_builder     = new TagBuilder(wrapRow.ToString());
                    var user_html_attributes = htmlListInfo.HtmlAttributes.ToDictionary();

                    // create raw style and merge it with user provided style (if applicable)
                    var defaultSectionStyle = "float:left;";     // margin-right:30px; line-height:25px;
                    if (textLayout == TextLayout.RightToLeft)
                    {
                        defaultSectionStyle += " text-align: right;";
                    }

                    object style;
                    user_html_attributes.TryGetValue("style", out style);
                    if (style != null)     // if user style is set, use it
                    {
                        wrapHtml_builder.MergeAttribute("style", defaultSectionStyle + " " + style);
                    }
                    else     // if not set, add only default style
                    {
                        wrapHtml_builder.MergeAttribute("style", defaultSectionStyle);
                    }

                    // merge it with other user provided attributes (e.g.: class)
                    user_html_attributes.Remove("style");
                    wrapHtml_builder.MergeAttributes(user_html_attributes);

                    // build wrapped raw html tag
                    htmlWrapInfo.WrapOpen     = wrapHtml_builder.ToString(TagRenderMode.StartTag);
                    htmlWrapInfo.WrapRowbreak = "</" + wrapRow + "> " +
                                                wrapHtml_builder.ToString(TagRenderMode.StartTag);
                    htmlWrapInfo.WrapClose = wrapHtml_builder.ToString(TagRenderMode.EndTag) +
                                             " <div style=\"clear:both;\"></div>";
                    htmlWrapInfo.AppendToElement = "<br/>";
                }
                break;

                // creates an html <table> with checkboxes sorted horizontally
                case HtmlTag.Table:
                {
                    if (htmlListInfo.Columns <= 0)
                    {
                        htmlListInfo.Columns = 1;
                    }
                    htmlWrapInfo.SeparatorMaxCount = htmlListInfo.Columns;

                    var wrapHtml_builder = new TagBuilder(HtmlElementTag.Table.ToString());
                    wrapHtml_builder.MergeAttributes(htmlListInfo.HtmlAttributes.ToDictionary());
                    wrapHtml_builder.MergeAttribute("cellspacing", "0");     // for IE7 compatibility

                    var wrapRow = HtmlElementTag.Tr;
                    htmlWrapInfo.WrapElement = HtmlElementTag.Td;
                    htmlWrapInfo.WrapOpen    = wrapHtml_builder.ToString(TagRenderMode.StartTag) +
                                               "<" + wrapRow + ">";
                    htmlWrapInfo.WrapRowbreak = "</" + wrapRow + "><" + wrapRow + ">";
                    htmlWrapInfo.WrapClose    = "</" + wrapRow + ">" +
                                                wrapHtml_builder.ToString(TagRenderMode.EndTag);
                }
                break;
                    //// creates an html unordered (bulleted) list of checkboxes in one column
                    //case HtmlTag.Ul:
                    //    {
                    //        var wrapHtml_builder = new TagBuilder(htmlElementTag.ul.ToString());
                    //        wrapHtml_builder.MergeAttributes(wrapInfo.htmlAttributes.ToDictionary());
                    //        wrapHtml_builder.MergeAttribute("cellspacing", "0"); // for IE7 compatibility

                    //        w.wrap_element = htmlElementTag.li;
                    //        w.wrap_open = wrapHtml_builder.ToString(TagRenderMode.StartTag);
                    //        w.wrap_close = wrapHtml_builder.ToString(TagRenderMode.EndTag);
                    //    }
                    //    break;
                }
            }
            // default setting creates vertical or horizontal column of checkboxes
            else
            {
                if (position == Position.Horizontal || position == Position.Horizontal_RightToLeft)
                {
                    htmlWrapInfo.AppendToElement = " &nbsp; ";
                }
                if (position == Position.Vertical || position == Position.Vertical_RightToLeft)
                {
                    htmlWrapInfo.AppendToElement = "<br/>";
                }

                if (textLayout == TextLayout.RightToLeft)
                {
                    // lean text to right for right-to-left languages
                    var defaultSectionStyle = "style=\"text-align: right;\"";
                    var wrapRow             = HtmlElementTag.Div;
                    htmlWrapInfo.WrapOpen     = "<" + wrapRow + " " + defaultSectionStyle + ">";
                    htmlWrapInfo.WrapRowbreak = string.Empty;
                    htmlWrapInfo.WrapClose    = "</" + wrapRow + ">";
                }
            }

            // return completed check box list wrapper
            return(htmlWrapInfo);
        }
Beispiel #10
0
        /// <summary>
        /// Create a Table Layout.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="htmlhelper"></param>
        /// <param name="viewModel">Model with List to Show and Properties to Show.</param>
        /// <param name="withEdit">A boolean type for create a Table with Edit button</param>
        /// <param name="withRemove">A boolean type for create a Table with Remove button</param>
        /// <param name="withDetail">A boolean type for create a Table with Detail button</param>
        /// <param name="htmlAttributes"></param>
        /// <returns></returns>
        public static MvcHtmlString TableListFor <TModel, TEntity>(this HtmlHelper <TModel> htmlhelper,
                                                                   ITableList <TEntity> viewModel,
                                                                   bool withEdit         = false,
                                                                   bool withRemove       = false,
                                                                   bool withDetail       = false,
                                                                   object htmlAttributes = null) where TEntity : class
        {
            TagBuilder table = new TagBuilder("table");

            table.AddCssClass("table table-bordered table-hover table-responsive");

            TagBuilder tr = new TagBuilder("tr");

            foreach (var propertyToShow in viewModel.PropertiesToShow)
            {
                TagBuilder th = new TagBuilder("th");

                th.MergeAttribute("style", "cursor: default; ");

                th.InnerHtml = propertyToShow.DisplayProperty != null ? propertyToShow.DisplayProperty : propertyToShow.PropertyName;

                tr.InnerHtml += th.ToString();
            }

            if (withEdit)
            {
                tr.InnerHtml += HtmlExtentionsCommon.CreateTagBuilder("th", "Editar", new { style = "width: 5%; cursor: default;" }).ToString();
            }

            if (withDetail)
            {
                tr.InnerHtml += HtmlExtentionsCommon.CreateTagBuilder("th", "Detalhes", new { style = "width: 5%; cursor: default" }).ToString();
            }

            if (withRemove)
            {
                tr.InnerHtml += HtmlExtentionsCommon.CreateTagBuilder("th", "Remover", new { style = "width: 5%; cursor: default" }).ToString();
            }

            TagBuilder tHead = HtmlExtentionsCommon.CreateTagBuilder("thead", tr.ToString());


            TagBuilder tbody = new TagBuilder("tbody");

            foreach (var item in viewModel.List)
            {
                TagBuilder trItem = new TagBuilder("tr");
                var        propertiesFromTheItem = item.GetType().GetProperties();

                foreach (var property in propertiesFromTheItem)
                {
                    PropertyToShow showThisProperty = HtmlExtentionsCommon.ShowThisProperty(property, viewModel.PropertiesToShow, item);


                    if (showThisProperty != null)
                    {
                        string display = showThisProperty.DisplayProperty != null ? showThisProperty.DisplayProperty : showThisProperty.PropertyName;

                        TagBuilder td = new TagBuilder("td");
                        td.InnerHtml = item.GetType().GetProperty(property.Name).GetValue(item).ToString();
                        td.MergeAttribute("style", "padding-top: 15px");
                        trItem.InnerHtml += td.ToString();
                    }
                }

                if (withEdit)
                {
                    var button = HtmlExtentionsCommon.CreateTagBuilder("td",
                                                                       ButtonHtmlExtention.Button(
                                                                           htmlhelper, string.Empty,
                                                                           "btn-info col-lg-12",
                                                                           "glyphicon glyphicon-edit",
                                                                           string.Empty,
                                                                           HtmlButtonTypes.Button,
                                                                           new { data_action = "editar", data_actionId = item.GetType().GetProperty("Id").GetValue(item).ToString(), title = "Editar" }
                                                                           ).ToString());

                    trItem.InnerHtml += button.ToString();
                }

                if (withDetail)
                {
                    var button = HtmlExtentionsCommon.CreateTagBuilder("td",
                                                                       ButtonHtmlExtention.Button(
                                                                           htmlhelper, string.Empty,
                                                                           "btn-success col-lg-10 col-lg-offset-1",
                                                                           "glyphicon glyphicon-search",
                                                                           string.Empty,
                                                                           HtmlButtonTypes.Button,
                                                                           new { data_action = "editar", data_actionId = item.GetType().GetProperty("Id").GetValue(item).ToString(), title = "Detalhe" }
                                                                           ).ToString());
                    trItem.InnerHtml += button.ToString();
                }

                if (withRemove)
                {
                    var button = HtmlExtentionsCommon.CreateTagBuilder("td",
                                                                       ButtonHtmlExtention.Button(
                                                                           htmlhelper, string.Empty,
                                                                           "btn-danger col-lg-10 col-lg-offset-1",
                                                                           "glyphicon glyphicon-trash",
                                                                           string.Empty,
                                                                           HtmlButtonTypes.Button,
                                                                           new { data_action = "remover", data_actionId = item.GetType().GetProperty("Id").GetValue(item).ToString(), title = "Remover" }
                                                                           ).ToString());
                    trItem.InnerHtml += button.ToString();
                }

                tbody.InnerHtml += trItem.ToString();
            }
            table.InnerHtml  = tHead.ToString();
            table.InnerHtml += tbody.ToString();

            if (htmlAttributes != null)
            {
                var anonymousObject = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);

                if (anonymousObject.Select(x => x.Value.ToString().Contains("margin")).FirstOrDefault())
                {
                    table.MergeAttributes(anonymousObject);
                }
                else
                {
                    anonymousObject.Add("style", "margin: 10px 0px");
                }
            }
            else if (htmlAttributes != null)
            {
                table.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(new { style = "margin: 10px 0px; form-group" }));
            }

            return(MvcHtmlString.Create(table.ToString()));
        }
Beispiel #11
0
        public static MvcHtmlString PageLinks(this HtmlHelper html, PagingInfo pagingInfo, Func <int, string> pageUrl)
        {
            StringBuilder stringBuilder = new StringBuilder();

            if (pagingInfo.TotalPages != 0)
            {
                TagBuilder tagBuilder = new TagBuilder("a")
                {
                    InnerHtml = "Previous"
                };
                if (pagingInfo.CurrentPage == 1)
                {
                    tagBuilder.MergeAttribute("class", "prev-disabled");
                }
                else
                {
                    tagBuilder.MergeAttribute("href", pageUrl(pagingInfo.CurrentPage - 1));
                }
                stringBuilder.Append(tagBuilder.ToString());
                if (pagingInfo.TotalPages >= 1)
                {
                    TagBuilder tagBuilder1 = new TagBuilder("a")
                    {
                        InnerHtml = "1"
                    };
                    tagBuilder1.MergeAttribute("href", pageUrl(1));
                    if (pagingInfo.CurrentPage == 1)
                    {
                        tagBuilder1.MergeAttribute("class", "current");
                    }
                    stringBuilder.Append(tagBuilder1.ToString());
                }
                if (pagingInfo.TotalPages >= 2)
                {
                    TagBuilder tagBuilder2 = new TagBuilder("a")
                    {
                        InnerHtml = "2"
                    };
                    tagBuilder2.MergeAttribute("href", pageUrl(2));
                    if (pagingInfo.CurrentPage == 2)
                    {
                        tagBuilder2.MergeAttribute("class", "current");
                    }
                    stringBuilder.Append(tagBuilder2.ToString());
                }
                if (pagingInfo.CurrentPage > 5 && pagingInfo.TotalPages != 6)
                {
                    TagBuilder tagBuilder3 = new TagBuilder("span")
                    {
                        InnerHtml = "..."
                    };
                    tagBuilder3.MergeAttribute("class", "text");
                    stringBuilder.Append(tagBuilder3.ToString());
                }
                if (pagingInfo.CurrentPage > 2)
                {
                    int currentPage = pagingInfo.CurrentPage;
                }
                if (pagingInfo.CurrentPage <= 5)
                {
                    for (int i = 3; i < 8 && i <= pagingInfo.TotalPages; i++)
                    {
                        TagBuilder tagBuilder4 = new TagBuilder("a")
                        {
                            InnerHtml = i.ToString()
                        };
                        tagBuilder4.MergeAttribute("href", pageUrl(i));
                        if (i == pagingInfo.CurrentPage)
                        {
                            tagBuilder4.MergeAttribute("class", "current");
                        }
                        stringBuilder.Append(tagBuilder4.ToString());
                    }
                    if (pagingInfo.TotalPages > 7)
                    {
                        TagBuilder tagBuilder5 = new TagBuilder("span")
                        {
                            InnerHtml = "..."
                        };
                        tagBuilder5.MergeAttribute("class", "text");
                        stringBuilder.Append(tagBuilder5.ToString());
                    }
                }
                if (pagingInfo.CurrentPage > 5 && pagingInfo.CurrentPage + 5 > pagingInfo.TotalPages)
                {
                    int totalPages = pagingInfo.TotalPages - 4;
                    if (totalPages == 2)
                    {
                        totalPages++;
                    }
                    for (int j = totalPages; j <= pagingInfo.TotalPages; j++)
                    {
                        TagBuilder tagBuilder6 = new TagBuilder("a")
                        {
                            InnerHtml = j.ToString()
                        };
                        tagBuilder6.MergeAttribute("href", pageUrl(j));
                        if (j == pagingInfo.CurrentPage)
                        {
                            tagBuilder6.MergeAttribute("class", "current");
                        }
                        stringBuilder.Append(tagBuilder6.ToString());
                    }
                }
                if (pagingInfo.CurrentPage > 5 && pagingInfo.CurrentPage + 5 <= pagingInfo.TotalPages)
                {
                    for (int k = pagingInfo.CurrentPage; k < pagingInfo.CurrentPage + 5; k++)
                    {
                        TagBuilder tagBuilder7 = new TagBuilder("a")
                        {
                            InnerHtml = (k - 2).ToString()
                        };
                        tagBuilder7.MergeAttribute("href", pageUrl(k - 2));
                        if (k == pagingInfo.CurrentPage + 2)
                        {
                            tagBuilder7.MergeAttribute("class", "current");
                        }
                        stringBuilder.Append(tagBuilder7.ToString());
                    }
                    TagBuilder tagBuilder8 = new TagBuilder("span")
                    {
                        InnerHtml = "..."
                    };
                    tagBuilder8.MergeAttribute("class", "text");
                    stringBuilder.Append(tagBuilder8.ToString());
                }
                TagBuilder tagBuilder9 = new TagBuilder("a")
                {
                    InnerHtml = "Next"
                };
                if (pagingInfo.CurrentPage == pagingInfo.TotalPages)
                {
                    tagBuilder9.MergeAttribute("class", "next-disabled");
                }
                else
                {
                    tagBuilder9.MergeAttribute("href", pageUrl(pagingInfo.CurrentPage + 1));
                }
                stringBuilder.Append(tagBuilder9.ToString());
            }
            return(MvcHtmlString.Create(stringBuilder.ToString()));
        }
        private static MvcHtmlString CKEditorHelper(HtmlHelper htmlHelper, ModelMetadata modelMetadata, string name, IDictionary <string, object> rowsAndColumns, IDictionary <string, object> htmlAttributes, string ckEditorConfigOptions)
        {
            string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);

            if (String.IsNullOrEmpty(fullName))
            {
                throw new ArgumentException("string parameter is null or empty", "name");
            }

            TagBuilder textAreaBuilder = new TagBuilder("textarea");

            textAreaBuilder.GenerateId(fullName);
            textAreaBuilder.MergeAttributes(htmlAttributes, true);
            textAreaBuilder.MergeAttribute("name", fullName, true);
            string style = "";

            if (textAreaBuilder.Attributes.ContainsKey("style"))
            {
                style = textAreaBuilder.Attributes["style"];
            }
            if (string.IsNullOrWhiteSpace(style))
            {
                style = "";
            }
            style += string.Format("height:{0}em; width:{1}em;", rowsAndColumns["rows"], rowsAndColumns["cols"]);
            textAreaBuilder.MergeAttribute("style", style, true);
            // If there are any errors for a named field, we add the CSS attribute.
            ModelState modelState;

            if (htmlHelper.ViewData.ModelState.TryGetValue(fullName, out modelState) && modelState.Errors.Count > 0)
            {
                textAreaBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);
            }

            textAreaBuilder.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(name));

            string value;

            if (modelState != null && modelState.Value != null)
            {
                value = modelState.Value.AttemptedValue;
            }
            else if (modelMetadata.Model != null)
            {
                value = modelMetadata.Model.ToString();
            }
            else
            {
                value = String.Empty;
            }

            // The first newline is always trimmed when a TextArea is rendered, so we add an extra one
            // in case the value being rendered is something like "\r\nHello".
            textAreaBuilder.SetInnerText(Environment.NewLine + value);

            TagBuilder scriptBuilder = new TagBuilder("script");

            scriptBuilder.MergeAttribute("type", "text/javascript");
            if (string.IsNullOrEmpty(ckEditorConfigOptions))
            {
                ckEditorConfigOptions = string.Format("{{ width:'{0}em', height:'{1}em', CKEDITOR.config.allowedContent : true }}", rowsAndColumns["cols"], rowsAndColumns["rows"]);
            }
            if (!ckEditorConfigOptions.Trim().StartsWith("{"))
            {
                ckEditorConfigOptions = "{" + ckEditorConfigOptions;
            }
            if (!ckEditorConfigOptions.Trim().EndsWith("}"))
            {
                ckEditorConfigOptions += "}";
            }
            scriptBuilder.InnerHtml = string.Format(" $('#{0}').ckeditor({1}).addClass('{2}'); ",
                                                    fullName,
                                                    ckEditorConfigOptions,
                                                    CK_Ed_Class
                                                    );
            return(MvcHtmlString.Create(textAreaBuilder.ToString() + "\n" + scriptBuilder.ToString()));
        }