Esempio n. 1
0
        /// <summary>
        /// Generates the HTML markup corresponding to a list of checkboxes.
        /// </summary>
        /// <typeparam name="TModel">The type of the model</typeparam>
        /// <typeparam name="T">The type of the elements of the enumeration. Use simple types</typeparam>
        /// <param name="htmlHelper"></param>
        /// <param name="expression">The lambda expression that yields an enumeration of Ts</param>
        /// <param name="namePrefix">Prefix to be used by the name for the generated checkboxes</param>
        /// <param name="items">List of available options to be displayed</param>
        /// <param name="htmlAttributes">An object whose properties will become attributes for the HTML main container element</param>
        /// <param name="cols">Number of columns in which the list will be arranged. Valid values range lies between 1 and 12</param>
        /// <returns></returns>
        public static MvcHtmlString MultiSelectFor<TModel, T>(
            this HtmlHelper<TModel> htmlHelper,
            Expression<Func<TModel, IEnumerable<T>>> expression, 
            IEnumerable<SelectListItem> items, 
            object htmlAttributes, 
            int cols = 1 ) {

            cols = (cols < 1 || cols > 12) ? 1 : cols;
            int rows = items.Count() % cols == 0 ? items.Count() / cols : 1 + items.Count() / cols;

            TagBuilder mainContainer = new TagBuilder("div");
            if(htmlAttributes != null) {
                foreach(PropertyInfo prop in htmlAttributes.GetType().GetProperties()) {
                    mainContainer.Attributes.Add(prop.Name, prop.GetValue(htmlAttributes).ToString());
                }
            }

            TagBuilder grid = new TagBuilder("div");
            grid.Attributes.Add("style", $"display: grid; grid.template-columns: {cols}; grid-template-rows: {rows}");


            ModelMetadata modelMetadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
            string prefix = htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix;

            string cboxName = String.IsNullOrWhiteSpace(prefix) ? 
                modelMetadata.PropertyName : 
                $"{prefix}.{modelMetadata.PropertyName}";

            int index = 0;
            StringBuilder gridContentBuilder = new StringBuilder();
            foreach(SelectListItem item in items) {
                int currentCol = 1 + index % cols;
                int currentRow = 1 + index / cols;

                TagBuilder div = new TagBuilder("div");
                div.Attributes.Add("style", $"grid-column-start: {currentCol}; grid-row-start: {currentRow}");

                TagBuilder checkbox = new TagBuilder("input");
                checkbox.Attributes.Add("type", "checkbox");
                checkbox.Attributes.Add("name", cboxName);
                checkbox.Attributes.Add("value", item.Value);
                if(item.Selected) {
                    checkbox.Attributes.Add("checked", "checked");
                }
                checkbox.GenerateId($"{cboxName}_{item.Value}");

                TagBuilder label = new TagBuilder("label");
                label.Attributes.Add("for", checkbox.Attributes["id"]);
                label.SetInnerText(item.Text);

                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.AppendLine(checkbox.ToString(TagRenderMode.SelfClosing));
                stringBuilder.AppendLine(label.ToString(TagRenderMode.Normal));

                div.InnerHtml = stringBuilder.ToString();

                gridContentBuilder.AppendLine(div.ToString(TagRenderMode.Normal));

                index++;
            }

            grid.InnerHtml = gridContentBuilder.ToString();
            mainContainer.InnerHtml = grid.ToString(TagRenderMode.Normal);

            return new MvcHtmlString(mainContainer.ToString(TagRenderMode.Normal));
        }
        private static MvcHtmlString CKEditorHelper(HtmlHelper htmlHelper, ModelMetadata modelMetadata, string name, string uploadUrl, IDictionary <string, object> rowsAndColumns, IDictionary <string, object> htmlAttributes, string ckEditorConfigOptions)
        {
            var fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
            var id       = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(name);

            var textAreaBuilder = new TagBuilder("textarea");

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

            if (textAreaBuilder.Attributes.ContainsKey("style"))
            {
                style = textAreaBuilder.Attributes["style"];
            }
            if (string.IsNullOrWhiteSpace(style))
            {
                style = "";
            }
            //style += string.Format("height:{0}em; width:{1}em; margin-bottom: 20px !important;", rowsAndColumns["rows"], rowsAndColumns["cols"]);
            style += string.Format("height:{0}em; width:100%; margin-bottom: 20px !important;", rowsAndColumns["rows"], rowsAndColumns["cols"]);
            textAreaBuilder.MergeAttribute("style", style, true);
            // If there are any errors for a named field, we add the CSS attribute.
            if (htmlHelper.ViewData.ModelState.TryGetValue(fullName, out ModelState modelState) && modelState.Errors.Count > 0)
            {
                textAreaBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);
            }

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

            string value;

            if (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);

            var scriptBuilder = new TagBuilder("script");

            scriptBuilder.MergeAttribute("type", "text/javascript");
            if (string.IsNullOrEmpty(ckEditorConfigOptions))
            {
                ckEditorConfigOptions = string.Format("{{ width:'100%', height:'{1}em', filebrowserImageUploadUrl:'{2}' }}", rowsAndColumns["cols"], rowsAndColumns["rows"], uploadUrl);
            }
            if (!ckEditorConfigOptions.Trim().StartsWith("{"))
            {
                ckEditorConfigOptions = "{" + ckEditorConfigOptions;
            }
            if (!ckEditorConfigOptions.Trim().EndsWith("}"))
            {
                ckEditorConfigOptions += "}";
            }
            scriptBuilder.InnerHtml = string.Format(" $('#{0}').ckeditor({1}).addClass('{2}'); ", id, ckEditorConfigOptions, CK_Ed_Class);

            //<script type=""text/javascript""> function UpdateCKEditors() { $('." + CK_Ed_Class + @"').ckeditorGet().updateElement(); } </script>"
            htmlHelper.ScriptFileSingle(@"<script src=""" + CK_Ed_Location + @"ckeditor.js""></script>");
            htmlHelper.ScriptFileSingle(@"<script src=""" + CK_Ed_Location + @"adapters/jquery.js""></script>");
            htmlHelper.Script(scriptBuilder.ToString());

            return(MvcHtmlString.Create(@"
<div class=""form-group"">
    <div class=""col-sm-12"">
    " + textAreaBuilder + @"
    </div>
</div>"));
        }
        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()));
        }