Beispiel #1
0
        public static MvcHtmlString Captcha(this HtmlHelper helper, string id, string title, object htmlAttributes)
        {
            TagBuilder tagBuilder = new TagBuilder("img");

            tagBuilder.GenerateId(id);
            tagBuilder.MergeAttribute("title", title);
            tagBuilder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
            return(MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.SelfClosing)));

            //var writer = new HtmlTextWriter(new StringWriter());
            //writer.AddAttribute(HtmlTextWriterAttribute.Alt, "验证码");
            ////writer.AddAttribute(HtmlTextWriterAttribute.Src, url);
            //writer.RenderBeginTag(HtmlTextWriterTag.Img);
            //writer.RenderEndTag();
            //return writer.InnerWriter.ToString();

            //return helper.ActionLink("", "Index", "Home");
        }
Beispiel #2
0
        public static MvcHtmlString Menu2(this HtmlHelper helper, string text, string title, string href = null, object htmlAttributes = null, object iconAttributes = null, bool disabled = false, bool permission = false, bool appNew = false)
        {
            TagBuilder _ibuilder   = null;
            TagBuilder _sbuilder   = null;
            TagBuilder _builder    = new TagBuilder("a");
            TagBuilder _pbuilder   = new TagBuilder("span");
            UrlHelper  _urlHelper  = new UrlHelper(helper.ViewContext.RequestContext);
            string     _controller = Extensions.NullToString(helper.ViewContext.RouteData.GetRequiredString("controller"));

            _builder.GenerateId("btn" + (string.IsNullOrEmpty(text) ? title : text));
            _builder.Attributes["title"]       = title;
            _builder.Attributes["data-widget"] = "view";
            _builder.Attributes["href"]        = "#";
            _builder.Attributes["data-href"]   = (href != null ? href : "#");

            if (disabled || permission)
            {
                _builder.Attributes["disabled"] = "disabled";
            }

            if (permission)
            {
                _builder.AddCssClass("text-disable");
            }

            if (appNew)
            {
                _sbuilder = new TagBuilder("span");
                _sbuilder.AddCssClass("badge pull-right bg-green");
                _sbuilder.InnerHtml = "new";
                _builder.InnerHtml  = string.Format("{0}{1}", _builder.InnerHtml, _sbuilder.ToString());
            }

            if (iconAttributes != null)
            {
                _ibuilder = new TagBuilder("i");
                _ibuilder.MergeAttributes(new RouteValueDictionary(HtmlHelper.AnonymousObjectToHtmlAttributes(iconAttributes)));
                _builder.InnerHtml = string.Format("{0}{1}", _builder.InnerHtml, _ibuilder.ToString());
            }
            _pbuilder.InnerHtml = text;
            _builder.InnerHtml  = string.Format("{0} {1}", _builder.InnerHtml, _pbuilder.ToString());
            _builder.MergeAttributes(new RouteValueDictionary(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)));
            return(MvcHtmlString.Create(_builder.ToString()));
        }
Beispiel #3
0
        public static MvcHtmlString RadioButtonAndLabelFor <TModel, TProperty>(this HtmlHelper <TModel> htmlHelper, Expression <Func <TModel, TProperty> > expression, object value, string labelText, object htmlAttributes)
        {
            // Retrieve the qualified model identifier
            string name     = ExpressionHelper.GetExpressionText(expression);
            string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);

            // Generate the base ID
            TagBuilder tagBuilder = new TagBuilder("input");

            tagBuilder.GenerateId(fullName);
            string idAttr = tagBuilder.Attributes["id"];

            idAttr = String.Format("{0}_{1}", idAttr, value);
            string label_fp = "<label class=\"custom-radio-button\">";
            string label_sp = string.Format("<span class=\"helping-el\"></span><span class=\"custom-radio-button-label\">{0}</span></label>", labelText);
            // Create the individual HTML elements, using the generated ID
            MvcHtmlString radioButton = htmlHelper.RadioButtonFor(expression, value, htmlAttributes);

            return(new MvcHtmlString(label_fp + radioButton.ToHtmlString() + label_sp));
        }
Beispiel #4
0
        public static MvcHtmlString ButtonAlert(this HtmlHelper helper, string text, string title, Action modal, string action, object htmlAttributes = null, object iconAttributes = null, string value = null, bool disabled = false)
        {
            TagBuilder _ibuilder   = null;
            TagBuilder _builder    = new TagBuilder("a");
            TagBuilder _pbuilder   = new TagBuilder("span");
            UrlHelper  _urlHelper  = new UrlHelper(helper.ViewContext.RequestContext);
            string     _controller = Extensions.NullToString(helper.ViewContext.RouteData.GetRequiredString("controller"));

            _builder.GenerateId("btn" + (string.IsNullOrEmpty(text) ? title : text));
            _builder.Attributes["title"]       = title;
            _builder.Attributes["data-widget"] = modal.GetValueAsString();
            _builder.Attributes["href"]        = "#";
            _builder.Attributes["data-href"]   = (action != null ? _urlHelper.Action(action, _controller) : "#");

            if (disabled)
            {
                _builder.Attributes["disabled"] = "disabled";
            }

            if (iconAttributes != null)
            {
                _ibuilder = new TagBuilder("i");
                _ibuilder.MergeAttributes(new RouteValueDictionary(HtmlHelper.AnonymousObjectToHtmlAttributes(iconAttributes)));
                _builder.InnerHtml = string.Format("{0}{1}", _builder.InnerHtml, _ibuilder.ToString());
            }

            if (value != null)
            {
                _pbuilder.InnerHtml = value;
                _pbuilder.MergeAttributes(new RouteValueDictionary(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)));
            }
            else
            {
                _pbuilder.InnerHtml = text;
            }
            _builder.InnerHtml = string.Format("{0} {1}", _builder.InnerHtml, _pbuilder.ToString());
            return(MvcHtmlString.Create(_builder.ToString()));
        }
Beispiel #5
0
        public static MvcHtmlString Button(this HtmlHelper helper, string text, string title, Action modal, object htmlAttributes = null, object iconAttributes = null, bool disabled = false)
        {
            TagBuilder _ibuilder  = null;
            TagBuilder _builder   = new TagBuilder("a");
            TagBuilder _pbuilder  = new TagBuilder("span");
            UrlHelper  _urlHelper = new UrlHelper(helper.ViewContext.RequestContext);

            _builder.GenerateId("btn" + (string.IsNullOrEmpty(title) ? text : title));
            _builder.Attributes["title"] = title;
            _builder.Attributes["href"]  = "#";

            if (modal.Equals(Action.Dismiss))
            {
                _builder.Attributes["data-dismiss"] = modal.GetValueAsString();
            }
            else
            {
                _builder.Attributes["data-widget"] = modal.GetValueAsString();
            }

            if (disabled)
            {
                _builder.Attributes["disabled"] = "disabled";
            }

            if (iconAttributes != null)
            {
                _ibuilder = new TagBuilder("i");
                _ibuilder.MergeAttributes(new RouteValueDictionary(HtmlHelper.AnonymousObjectToHtmlAttributes(iconAttributes)));
                _builder.InnerHtml = string.Format("{0}{1}", _builder.InnerHtml, _ibuilder.ToString());
            }
            _pbuilder.InnerHtml = text;
            _builder.InnerHtml  = string.Format("{0} {1}", _builder.InnerHtml, _pbuilder.ToString());
            _builder.MergeAttributes(new RouteValueDictionary(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)));
            return(MvcHtmlString.Create(_builder.ToString()));
        }
        /// <summary>
        /// Validations the summary.
        /// </summary>
        /// <param name="htmlHelper">The HTML helper.</param>
        /// <param name="groupName">Name of the group.</param>
        /// <param name="excludePropertyErrors">if set to <c>true</c> [exclude property errors].</param>
        /// <param name="message">The message.</param>
        /// <param name="htmlAttributes">The HTML attributes.</param>
        /// <returns></returns>
        public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, string groupName, bool excludePropertyErrors, string message, IDictionary <string, object> htmlAttributes)
        {
            #region Validate Arguments
            if (htmlHelper == null)
            {
                throw new ArgumentNullException("htmlHelper");
            }
            groupName = groupName ?? string.Empty;
            #endregion

            string[] groupNames = groupName.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToArray();

            if (htmlAttributes == null)
            {
                htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(null);
            }
            htmlAttributes["data-val-valgroup-name"] = groupName;



            object model = htmlHelper.ViewData.Model;
            ModelStateDictionary modelState = htmlHelper.ViewData.ModelState;

            bool canValidate = !modelState.ContainsKey(ValidationGroupsKey) ||
                               (groupNames.Any() && ((IEnumerable <string>)modelState[ValidationGroupsKey].Value.RawValue).Intersect(groupNames).Any()) ||
                               (!groupNames.Any());
            IEnumerable <ModelState> faulted           = canValidate ? GetFaultedModelStates(htmlHelper, groupNames, model) : Enumerable.Empty <ModelState>();
            FormContext formContextForClientValidation = htmlHelper.ViewContext.ClientValidationEnabled ? htmlHelper.ViewContext.FormContext : null;
            if (!canValidate || !faulted.Any())
            {
                if (formContextForClientValidation == null)
                {
                    return(null);
                }
            }
            string str = InitializeResponseString(message);

            IEnumerable <ModelState> values = GetValues(htmlHelper, excludePropertyErrors, modelState, faulted);
            TagBuilder builder3             = AddValidationMessages(htmlHelper, values);
            TagBuilder tagBuilder           = new TagBuilder("div");
            tagBuilder.MergeAttributes <string, object>(htmlAttributes);
            tagBuilder.AddCssClass("validation-summary");
            tagBuilder.AddCssClass(!faulted.Any() ? HtmlHelper.ValidationSummaryValidCssClassName : HtmlHelper.ValidationSummaryCssClassName);
            tagBuilder.InnerHtml = str + builder3.ToString(TagRenderMode.Normal);
            if (formContextForClientValidation != null)
            {
                if (htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled)
                {
                    if (!excludePropertyErrors)
                    {
                        tagBuilder.MergeAttribute("data-valmsg-summary", "true");
                    }
                }
                else
                {
                    tagBuilder.GenerateId("validationSummary");
                    formContextForClientValidation.ValidationSummaryId      = tagBuilder.Attributes["id"];
                    formContextForClientValidation.ReplaceValidationSummary = !excludePropertyErrors;
                }
            }
            return(new MvcHtmlString(tagBuilder.ToString(TagRenderMode.Normal)));
        }
Beispiel #7
0
        private static MvcHtmlString BootstrapInputHelper(HtmlHelper htmlHelper, InputType inputType, ModelMetadata metadata, string name, object value, bool useViewData, bool isChecked, bool setId, bool isExplicitValue, IDictionary <string, object> htmlAttributes, string blockHelpText)
        {
            string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);

            if (String.IsNullOrEmpty(fullName))
            {
                throw new ArgumentException("Value cannot be null or empty.", "name");
            }

            TagBuilder tagBuilder = new TagBuilder("input");

            tagBuilder.MergeAttributes(htmlAttributes);
            tagBuilder.MergeAttribute("type", HtmlHelper.GetInputTypeString(inputType));
            tagBuilder.MergeAttribute("name", fullName, true);

            string valueParameter = Convert.ToString(value, CultureInfo.CurrentCulture);
            bool   usedModelState = false;

            switch (inputType)
            {
            case InputType.CheckBox:
                bool?modelStateWasChecked = htmlHelper.GetModelStateValue(fullName, typeof(bool)) as bool?;
                if (modelStateWasChecked.HasValue)
                {
                    isChecked      = modelStateWasChecked.Value;
                    usedModelState = true;
                }
                goto case InputType.Radio;

            case InputType.Radio:
                if (!usedModelState)
                {
                    string modelStateValue = htmlHelper.GetModelStateValue(fullName, typeof(string)) as string;
                    if (modelStateValue != null)
                    {
                        isChecked      = String.Equals(modelStateValue, valueParameter, StringComparison.Ordinal);
                        usedModelState = true;
                    }
                }
                if (!usedModelState && useViewData)
                {
                    isChecked = htmlHelper.EvalBoolean(fullName);
                }
                if (isChecked)
                {
                    tagBuilder.MergeAttribute("checked", "checked");
                }
                tagBuilder.MergeAttribute("value", valueParameter, isExplicitValue);
                break;

            case InputType.Password:
                if (value != null)
                {
                    tagBuilder.MergeAttribute("value", valueParameter, isExplicitValue);
                }
                break;

            default:
                string attemptedValue = (string)htmlHelper.GetModelStateValue(fullName, typeof(string));
                tagBuilder.MergeAttribute("value", attemptedValue ?? ((useViewData) ? htmlHelper.EvalString(fullName) : valueParameter), isExplicitValue);
                break;
            }

            if (setId)
            {
                tagBuilder.GenerateId(fullName);
            }

            // 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)
                {
                    tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);
                }
            }

            tagBuilder.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(name, metadata));

            if (inputType == InputType.CheckBox)
            {
                // Render an additional <input type="hidden".../> for checkboxes. This
                // addresses scenarios where unchecked checkboxes are not sent in the request.
                // Sending a hidden input makes it possible to know that the checkbox was present
                // on the page when the request was submitted.
                StringBuilder inputItemBuilder = new StringBuilder();
                inputItemBuilder.Append(tagBuilder.ToString(TagRenderMode.SelfClosing));

                TagBuilder hiddenInput = new TagBuilder("input");
                hiddenInput.MergeAttribute("type", HtmlHelper.GetInputTypeString(InputType.Hidden));
                hiddenInput.MergeAttribute("name", fullName);
                hiddenInput.MergeAttribute("value", "false");
                inputItemBuilder.Append(hiddenInput.ToString(TagRenderMode.SelfClosing));
                return(MvcHtmlString.Create(inputItemBuilder.ToString()));
            }
            else if (!String.IsNullOrEmpty(blockHelpText))
            {
                // Render an additional <span class="help-block"> inside
                // the <input ...> for the help text
                StringBuilder inputItemBuilder = new StringBuilder();
                inputItemBuilder.Append(tagBuilder.ToString(TagRenderMode.StartTag));

                TagBuilder span = new TagBuilder("span");
                span.MergeAttribute("class", "help-block");
                inputItemBuilder.Append(span.ToString(TagRenderMode.StartTag));
                inputItemBuilder.Append(blockHelpText);
                inputItemBuilder.Append(span.ToString(TagRenderMode.EndTag));
                inputItemBuilder.Append(tagBuilder.ToString(TagRenderMode.EndTag));

                return(MvcHtmlString.Create(inputItemBuilder.ToString()));
            }

            return(new MvcHtmlString(tagBuilder.ToString(TagRenderMode.SelfClosing)));
        }
        public static IHtmlString ValidationMessage(this HtmlHelper htmlHelper, ModelMetadata modelMetadata, IDictionary <string, object> htmlAttributes)
        {
            htmlAttributes = htmlAttributes ?? new RouteValueDictionary();
            var    validationMessage = "";
            string fullHtmlFieldName = htmlAttributes["name"] == null ? modelMetadata.PropertyName : htmlAttributes["name"].ToString();

            if (!string.IsNullOrEmpty(htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix))
            {
                fullHtmlFieldName = htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix + "." + fullHtmlFieldName;
            }
            FormContext formContextForClientValidation = htmlHelper.ViewContext.FormContext;
            //if (htmlHelper.ViewContext.ClientValidationEnabled)
            //{
            //    formContextForClientValidation = htmlHelper.ViewContext.FormContext;
            //}
            //if (!htmlHelper.ViewData.ModelState.ContainsKey(fullHtmlFieldName) && (formContextForClientValidation == null))
            //{
            //    return null;
            //}
            ModelState           modelState = htmlHelper.ViewData.ModelState[fullHtmlFieldName];
            ModelErrorCollection errors     = (modelState == null) ? null : modelState.Errors;
            ModelError           error      = ((errors == null) || (errors.Count == 0)) ? null : errors[0];

            if ((error == null) && (formContextForClientValidation == null))
            {
                return(null);
            }
            TagBuilder builder = new TagBuilder("span");

            builder.MergeAttributes <string, object>(htmlAttributes);
            builder.AddCssClass((error != null) ? HtmlHelper.ValidationMessageCssClassName : HtmlHelper.ValidationMessageValidCssClassName);
            if (!string.IsNullOrEmpty(validationMessage))
            {
                builder.SetInnerText(validationMessage);
            }
            else if (error != null)
            {
                builder.SetInnerText(GetUserErrorMessageOrDefault(htmlHelper.ViewContext.HttpContext, error, modelState));
            }
            if (formContextForClientValidation != null)
            {
                bool replaceValidationMessageContents = String.IsNullOrEmpty(validationMessage);

                FieldValidationMetadata fieldMetadata = ApplyFieldValidationMetadata(htmlHelper, modelMetadata, fullHtmlFieldName);
                // rules will already have been written to the metadata object
                fieldMetadata.ReplaceValidationMessageContents = replaceValidationMessageContents; // only replace contents if no explicit message was specified

                if (htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled)
                {
                    builder.MergeAttribute("data-valmsg-for", fullHtmlFieldName);
                    builder.MergeAttribute("data-valmsg-replace", replaceValidationMessageContents.ToString().ToLowerInvariant());
                }
                else
                {
                    // client validation always requires an ID
                    builder.GenerateId(fullHtmlFieldName + "_validationMessage");
                    fieldMetadata.ValidationMessageId = builder.Attributes["id"];
                }
            }

            //if (formContext != null)
            //{
            //    bool replaceValidationMessageContents = String.IsNullOrEmpty(validationMessage);

            //    FieldValidationMetadata fieldMetadata = ApplyFieldValidationMetadata(htmlHelper, modelMetadata, modelName);
            //    // rules will already have been written to the metadata object
            //    fieldMetadata.ReplaceValidationMessageContents = replaceValidationMessageContents; // only replace contents if no explicit message was specified

            //    if (htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled)
            //    {
            //        builder.MergeAttribute("data-valmsg-for", modelName);
            //        builder.MergeAttribute("data-valmsg-replace", replaceValidationMessageContents.ToString().ToLowerInvariant());
            //    }
            //    else
            //    {
            //        // client validation always requires an ID
            //        builder.GenerateId(modelName + "_validationMessage");
            //        fieldMetadata.ValidationMessageId = builder.Attributes["id"];
            //    }
            //}
            return(new HtmlString(builder.ToString(TagRenderMode.Normal)));
        }
        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' }}", 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()));
        }
Beispiel #10
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);
        }
        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>"));
        }
Beispiel #12
0
        /// <summary>
        /// render paging control
        /// </summary>
        /// <returns></returns>
        public String RenderPager()
        {
            //return null if total page count less than or equal to 1
            if (_NoOfPages <= 1 && _pagerOptions.AutoHide)
            {
                return(CopyrightText);
            }
            //Display error message if pageIndex out of range
            if ((_pageIndex > _NoOfPages && _NoOfPages > 0) || _pageIndex < 1)
            {
                return(String.Format("{0}<div style=\"color:red;font-weight:bold\">{1}</div>{0}",
                                     CopyrightText, _pagerOptions.PageIndexOutOfRangeErrorMessage));
            }


            var pagerItems = new List <PagerItem>();

            //First page
            if (_pagerOptions.ShowFirstLast)
            {
                AddFirst(pagerItems);
            }

            // Prev page
            if (_pagerOptions.ShowPrevNext)
            {
                AddPrevious(pagerItems);
            }


            if (_pagerOptions.ShowNumericPagerItems)
            {
                if (_pagerOptions.AlwaysShowFirstLastPageNumber && _startPageIndex > 1)
                {
                    pagerItems.Add(new PagerItem("1", 1, false, PagerItemType.NumericPage));
                }

                // more page before numeric page buttons
                if (_pagerOptions.ShowMorePagerItems)
                {
                    AddMoreBefore(pagerItems);
                }

                // numeric page
                AddPageNumbers(pagerItems);

                // more page after numeric page buttons
                if (_pagerOptions.ShowMorePagerItems)
                {
                    AddMoreAfter(pagerItems);
                }

                if (_pagerOptions.AlwaysShowFirstLastPageNumber && _endPageIndex < _NoOfPages)
                {
                    pagerItems.Add(new PagerItem(_NoOfPages.ToString(), _NoOfPages, false,
                                                 PagerItemType.NumericPage));
                }
            }

            // Next page
            if (_pagerOptions.ShowPrevNext)
            {
                AddNext(pagerItems);
            }

            //Last page
            if (_pagerOptions.ShowFirstLast)
            {
                AddLast(pagerItems);
            }

            var sb = new StringBuilder();

            if (_msAjaxPaging)
            {
                foreach (PagerItem item in pagerItems)
                {
                    sb.Append(GenerateMsAjaxPagerElement(item));
                }
            }
            else if (_pagerOptions.UseJqueryAjax)
            {
                foreach (PagerItem item in pagerItems)
                {
                    sb.Append(GenerateJqAjaxPagerElement(item));
                }
            }
            else
            {
                foreach (PagerItem item in pagerItems)
                {
                    sb.Append(GeneratePagerElement(item));
                }
            }

            var tb = new TagBuilder(_pagerOptions.ContainerTagName);

            if (_pagerOptions.Id.IsNotNullOrEmpty())
            {
                tb.GenerateId(_pagerOptions.Id);
            }
            if (_pagerOptions.CssClass.IsNotNullOrEmpty())
            {
                tb.AddCssClass(_pagerOptions.CssClass);
            }
            if (_pagerOptions.HorizontalAlign.IsNotNullOrEmpty())
            {
                var strAlign = "text-align:" + _pagerOptions.HorizontalAlign.ToLower();
                if (_htmlAttributes == null)
                {
                    _htmlAttributes = new RouteValueDictionary {
                        { "style", strAlign }
                    };
                }
                else
                {
                    if (_htmlAttributes.Keys.Contains("style"))
                    {
                        _htmlAttributes["style"] += ";" + strAlign;
                    }
                }
            }
            tb.MergeAttributes(_htmlAttributes, true);
            var scriptPager = String.Empty;

            if (_pagerOptions.UseJqueryAjax &&
                (String)_htmlHelper.ViewContext.HttpContext.Items[JqueryScriptCheckItemKey] != "1")
            {
                scriptPager = JqCheckScript;
                _htmlHelper.ViewContext.HttpContext.Items[JqueryScriptCheckItemKey] = "1";
            }
            if (_pagerOptions.ShowPageIndexBox)
            {
                sb.Append(BuildGoToPageSection(ref scriptPager));
            }
            else
            {
                sb.Length -= _pagerOptions.SeparatorHtml.Length;
            }
            tb.InnerHtml = sb.ToString();

            if (scriptPager.IsNotNullOrEmpty())
            {
                scriptPager = String.Concat("<script language=\"javascript\" type=\"text/javascript\">", scriptPager, "</script>");
            }
            return(String.Concat(CopyrightText, scriptPager, tb.ToString(TagRenderMode.Normal), CopyrightText));
        }
Beispiel #13
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));
        }