public void ValidationMessageReturnsNullForInvalidName()
        {
            // Arrange
            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());

            // Act
            MvcHtmlString html = htmlHelper.ValidationMessage("boo");

            // Assert
            Assert.Null(html);
        }
        public void ValidationMessageWithModelStateAndNoErrors()
        {
            // Arrange
            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());

            // Act
            MvcHtmlString html = htmlHelper.ValidationMessage("baz");

            // Assert
            Assert.Null(html);
        }
        public void ValidationMessageReturnsWithCustomMessage()
        {
            // Arrange
            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());

            // Act
            MvcHtmlString html = htmlHelper.ValidationMessage("foo", "bar error");

            // Assert
            Assert.Equal(@"<span class=""field-validation-error"">bar error</span>", html.ToHtmlString());
        }
        public void ValidationMessageReturnsWithCustomMessageAndObjectAttributesWithUnderscores()
        {
            // Arrange
            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());

            // Act
            MvcHtmlString html = htmlHelper.ValidationMessage("foo", "bar error", new { foo_baz = "baz" });

            // Assert
            Assert.Equal(@"<span class=""field-validation-error"" foo-baz=""baz"">bar error</span>", html.ToHtmlString());
        }
        public void ValidationMessageReturnsGenericMessageInsteadOfExceptionText()
        {
            // Arrange
            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());

            // Act
            MvcHtmlString html = htmlHelper.ValidationMessage("quux");

            // Assert
            Assert.Equal(@"<span class=""field-validation-error"">The value &#39;quuxValue&#39; is invalid.</span>", html.ToHtmlString());
        }
        public void ValidationMessageReturnsNullForNullModelState()
        {
            // Arrange
            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithNullModelState());

            // Act
            MvcHtmlString html = htmlHelper.ValidationMessage("foo");

            // Assert
            Assert.Null(html);
        }
        public void ValidationMessageReturnsFirstErrorWithMessage()
        {
            // Arrange
            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());

            // Act
            MvcHtmlString html = htmlHelper.ValidationMessage("foo");

            // Assert
            Assert.Equal(@"<span class=""field-validation-error"">foo error &lt;1&gt;</span>", html.ToHtmlString());
        }
        public void ValidationMessageWithModelStateAndNoErrors()
        {
            // Arrange
            HtmlHelper htmlHelper = HtmlHelperFactory.Create(GetModelStateWithErrors());

            // Act
            var html = htmlHelper.ValidationMessage("baz");

            // Assert
            Assert.Equal(@"<span class=""field-validation-valid"" data-valmsg-for=""baz"" data-valmsg-replace=""true""></span>", html.ToString());
        }
        public void ValidationMessageReturnsWithCustomMessageAndObjectAttributes()
        {
            // Arrange
            HtmlHelper htmlHelper = HtmlHelperFactory.Create(GetModelStateWithErrors());

            // Act
            var html = htmlHelper.ValidationMessage("foo", "bar error", new { baz = "baz" });

            // Assert
            Assert.Equal(@"<span baz=""baz"" class=""field-validation-error"" data-valmsg-for=""foo"" data-valmsg-replace=""false"">bar error</span>", html.ToHtmlString());
        }
        public void ValidationMessageReturnsFirstError()
        {
            // Arrange
            HtmlHelper htmlHelper = HtmlHelperFactory.Create(GetModelStateWithErrors());

            // Act
            var html = htmlHelper.ValidationMessage("foo");

            // Assert
            Assert.Equal(@"<span class=""field-validation-error"" data-valmsg-for=""foo"" data-valmsg-replace=""true"">foo error &lt;1&gt;</span>", html.ToHtmlString());
        }
        public void ValidationMessageReturnsWithObjectAttributes()
        {
            // Arrange
            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());

            // Act
            MvcHtmlString html = htmlHelper.ValidationMessage("foo", new { bar = "bar" });

            // Assert
            Assert.Equal(@"<span bar=""bar"" class=""field-validation-error"">foo error &lt;1&gt;</span>", html.ToHtmlString());
        }
        public static MvcHtmlString CValidationMessage(
            this HtmlHelper html,
            string modelName,
            string validationMessage = null,
            object htmlAttributes    = null)
        {
            IDictionary <string, object> attributes = null;

            addCustomClass(htmlAttributes, out attributes, "help-block");

            return(html.ValidationMessage(modelName, validationMessage, attributes));
        }
Example #13
0
        public void ValidationMessageWithClientValidation_ExplicitMessage_Valid()
        {
            var originalProviders = ModelValidatorProviders.Providers.ToArray();

            ModelValidatorProviders.Providers.Clear();

            try
            {
                // Arrange
                HtmlHelper  htmlHelper  = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());
                FormContext formContext = new FormContext();
                htmlHelper.ViewContext.ClientValidationEnabled = true;
                htmlHelper.ViewContext.FormContext             = formContext;

                ModelClientValidationRule[] expectedValidationRules = new ModelClientValidationRule[]
                {
                    new ModelClientValidationRule()
                    {
                        ValidationType = "ValidationRule1"
                    },
                    new ModelClientValidationRule()
                    {
                        ValidationType = "ValidationRule2"
                    }
                };

                Mock <ModelValidator> mockValidator = new Mock <ModelValidator>(ModelMetadata.FromStringExpression("", htmlHelper.ViewContext.ViewData), htmlHelper.ViewContext);
                mockValidator.Setup(v => v.GetClientValidationRules())
                .Returns(expectedValidationRules);
                Mock <ModelValidatorProvider> mockValidatorProvider = new Mock <ModelValidatorProvider>();
                mockValidatorProvider.Setup(vp => vp.GetValidators(It.IsAny <ModelMetadata>(), It.IsAny <ControllerContext>()))
                .Returns(new[] { mockValidator.Object });
                ModelValidatorProviders.Providers.Add(mockValidatorProvider.Object);

                // Act
                MvcHtmlString html = htmlHelper.ValidationMessage("baz", "some explicit message"); // 'baz' is valid

                // Assert
                Assert.Equal(@"<span class=""field-validation-valid"" id=""baz_validationMessage"">some explicit message</span>", html.ToHtmlString());
                Assert.NotNull(formContext.GetValidationMetadataForField("baz"));
                Assert.Equal("baz_validationMessage", formContext.FieldValidators["baz"].ValidationMessageId);
                Assert.False(formContext.FieldValidators["baz"].ReplaceValidationMessageContents);
                Assert.Equal(expectedValidationRules, formContext.FieldValidators["baz"].ValidationRules.ToArray());
            }
            finally
            {
                ModelValidatorProviders.Providers.Clear();
                foreach (var provider in originalProviders)
                {
                    ModelValidatorProviders.Providers.Add(provider);
                }
            }
        }
        public void ValidationMessageReturnsWithObjectAttributes()
        {
            // Arrange
            HtmlHelper htmlHelper = HtmlHelperFactory.Create(GetModelStateWithErrors());

            // Act
            var html = htmlHelper.ValidationMessage("foo", new { attr = "attr-value" });

            // Assert
            Assert.Equal("<span attr=\"attr-value\" class=\"field-validation-error\" data-valmsg-for=\"foo\" data-valmsg-replace=\"true\">foo error &lt;1&gt;</span>",
                         html.ToHtmlString());
        }
        internal static string ObjectTemplate(HtmlHelper html, AngularTemplateHelpers.TemplateHelperDelegate templateHelper)
        {
            var viewData      = html.ViewContext.ViewData;
            var templateInfo  = viewData.TemplateInfo;
            var modelMetadata = viewData.ModelMetadata;
            var stringBuilder = new StringBuilder();

            if (templateInfo.TemplateDepth > 1)
            {
                if (modelMetadata.Model != null)
                {
                    return(modelMetadata.SimpleDisplayText);
                }
                else
                {
                    return(modelMetadata.NullDisplayText);
                }
            }
            // basic template for a form field that is aware of Bootstrap styles and angular form settings
            foreach (var metadata in modelMetadata.Properties.Where(pm => ShouldShow(pm, templateInfo)))
            {
                if (!metadata.HideSurroundingHtml)
                {
                    // bootstrap form-group
                    stringBuilder.Append("<div class=\"form-group\">");
                    // Label text
                    var labeltext = LabelHelperInternal(html, metadata, metadata.PropertyName, null, new Dictionary <string, object>()
                    {
                        { "class", "col-md-2 control-label" }
                    }).ToHtmlString();
                    if (!string.IsNullOrEmpty(labeltext))
                    {
                        stringBuilder.AppendFormat(CultureInfo.InvariantCulture, "{0}\r\n", labeltext);
                    }
                    stringBuilder.Append("<div class=\"col-md-10\">");
                }
                // Core element
                stringBuilder.Append(templateHelper(html, metadata, metadata.PropertyName, null, DataBoundControlMode.Edit, null));
                // End surrounding
                if (!metadata.HideSurroundingHtml)
                {
                    stringBuilder.Append("</div>\r\n");
                    // Bootstrap style help block with private extension
                    stringBuilder.AppendFormat("<span class=\"help-block-dynamic\">{0}</span>", metadata.Description);
                    stringBuilder.Append(" ");
                    stringBuilder.Append("<div class=\"col-md-offset-2\">");
                    stringBuilder.Append(html.ValidationMessage(metadata.PropertyName));
                    stringBuilder.Append("</div>\r\n");
                    stringBuilder.Append("</div>\r\n");
                }
            }
            return(stringBuilder.ToString());
        }
 /// <summary>
 /// Creates a label, validation message and custom editor for an Rebel property and ensures it is styled correctly
 /// </summary>
 /// <param name="html">The HTML.</param>
 /// <param name="expression">The expression.</param>
 /// <param name="description">The description.</param>
 /// <param name="tooltip">The tooltip.</param>
 /// <returns></returns>
 public static IHtmlString UmbEditor(
     this HtmlHelper html,
     string expression,
     string description = "",
     string tooltip     = "")
 {
     return(UmbEditorMarkup(html.Label(expression),
                            html.Editor(expression),
                            html.ValidationMessage(expression),
                            description,
                            tooltip));
 }
        public static string RenderCheckBox(HtmlHelper html, BootstrapCheckBoxModel model)
        {
            model.htmlAttributes.MergeHtmlAttributes(html.GetUnobtrusiveValidationAttributes(model.htmlFieldName, model.metadata));
            if (model.tooltipConfiguration != null)
            {
                model.htmlAttributes.MergeHtmlAttributes(model.tooltipConfiguration.ToDictionary());
            }
            if (model.tooltip != null)
            {
                model.htmlAttributes.MergeHtmlAttributes(model.tooltip.ToDictionary());
            }
            var mergedHtmlAttrs = string.IsNullOrEmpty(model.id) ? model.htmlAttributes : model.htmlAttributes.AddOrReplace("id", model.id);

            string validationMessage = "";

            if (model.displayValidationMessage && html.ValidationMessage(model.htmlFieldName) != null)
            {
                string validation = html.ValidationMessage(model.htmlFieldName).ToHtmlString();
                validationMessage = new BootstrapHelpText(validation, model.validationMessageStyle).ToHtmlString();
            }
            return(html.CheckBox(model.htmlFieldName, model.isChecked, mergedHtmlAttrs.FormatHtmlAttributes()).ToHtmlString() + validationMessage);
        }
        public static string RenderCheckBox(HtmlHelper html, BootstrapCheckBoxModel model)
        {
            if (model.tooltipConfiguration != null) model.htmlAttributes.AddRange(model.tooltipConfiguration.ToDictionary());
            var mergedHtmlAttrs = string.IsNullOrEmpty(model.id) ? model.htmlAttributes : model.htmlAttributes.AddOrReplace("id", model.id);

            string validationMessage = "";
            if (model.displayValidationMessage)
            {
                string validation = html.ValidationMessage(model.htmlFieldName).ToHtmlString();
                validationMessage = new BootstrapHelpText(validation, model.validationMessageStyle).ToHtmlString();
            }
            return html.CheckBox(model.htmlFieldName, model.isChecked, mergedHtmlAttrs.FormatHtmlAttributes()).ToHtmlString() + validationMessage;
        }
        public void ValidationMessageUsesValidCssClassIfFieldDoesNotHaveErrors()
        {
            // Arrange
            HtmlHelper htmlHelper = HtmlHelperFactory.Create(GetModelStateWithErrors());

            // Act
            var html = htmlHelper.ValidationMessage("baz");

            // Assert
            Assert.Equal(
                "<span class=\"field-validation-valid\" data-valmsg-for=\"baz\" data-valmsg-replace=\"true\"></span>",
                html.ToString()
                );
        }
        public void ValidationMessageReturnsWithCustomMessage()
        {
            // Arrange
            HtmlHelper htmlHelper = HtmlHelperFactory.Create(GetModelStateWithErrors());

            // Atc
            var html = htmlHelper.ValidationMessage("foo", "bar error");

            // Assert
            Assert.Equal(
                "<span class=\"field-validation-error\" data-valmsg-for=\"foo\" data-valmsg-replace=\"false\">bar error</span>",
                html.ToHtmlString()
                );
        }
        public void ValidationMessageAllowsEmptyModelName()
        {
            // Arrange
            ModelStateDictionary dictionary = new ModelStateDictionary();

            dictionary.AddError("test", "some error text");
            HtmlHelper htmlHelper = HtmlHelperFactory.Create(dictionary);

            // Act
            var html = htmlHelper.ValidationMessage("test");

            // Assert
            Assert.Equal("<span class=\"field-validation-error\" data-valmsg-for=\"test\" data-valmsg-replace=\"true\">some error text</span>", html.ToHtmlString());
        }
        public static string RenderTextArea(HtmlHelper html, BootstrapTextAreaModel model)
        {
            if (model == null || string.IsNullOrEmpty(model.htmlFieldName)) return null;

            string validationMessage = "";
            if (model.displayValidationMessage)
            {
                string validation = html.ValidationMessage(model.htmlFieldName).ToHtmlString();
                validationMessage = new BootstrapHelpText(validation, model.validationMessageStyle).ToHtmlString();
            }
            if(!string.IsNullOrEmpty(model.id)) model.htmlAttributes.AddOrReplace("id", model.id);
            if (model.tooltipConfiguration != null) model.htmlAttributes.AddRange(model.tooltipConfiguration.ToDictionary());
            return html.TextArea(model.htmlFieldName, model.value, model.rows, model.columns, model.htmlAttributes.FormatHtmlAttributes()).ToHtmlString() + validationMessage;
        }
        public void ValidationMessageAllowsEmptyModelName()
        {
            // Arrange
            ViewDataDictionary vdd = new ViewDataDictionary();

            vdd.ModelState.AddModelError("", "some error text");
            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(vdd);

            // Act
            MvcHtmlString html = htmlHelper.ValidationMessage("");

            // Assert
            Assert.AreEqual(@"<span class=""field-validation-error"">some error text</span>", html.ToHtmlString());
        }
        public void ValidationMessageAllowsEmptyModelName()
        {
            // Arrange
            ModelStateDictionary dictionary = new ModelStateDictionary();

            dictionary.AddError("test", "some error text");
            HtmlHelper htmlHelper = new HtmlHelper(dictionary);

            // Act
            var html = htmlHelper.ValidationMessage("test");

            // Assert
            Assert.AreEqual(@"<span class=""field-validation-error"">some error text</span>", html.ToHtmlString());
        }
Example #25
0
        public void ValidationMessageWithClientValidation_DefaultMessage_Valid_Unobtrusive()
        {
            var originalProviders = ModelValidatorProviders.Providers.ToArray();

            ModelValidatorProviders.Providers.Clear();

            try
            {
                // Arrange
                HtmlHelper  htmlHelper  = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());
                FormContext formContext = new FormContext();
                htmlHelper.ViewContext.ClientValidationEnabled      = true;
                htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled = true;
                htmlHelper.ViewContext.FormContext = formContext;

                ModelClientValidationRule[] expectedValidationRules = new ModelClientValidationRule[]
                {
                    new ModelClientValidationRule()
                    {
                        ValidationType = "ValidationRule1"
                    },
                    new ModelClientValidationRule()
                    {
                        ValidationType = "ValidationRule2"
                    }
                };

                Mock <ModelValidator> mockValidator = new Mock <ModelValidator>(ModelMetadata.FromStringExpression("", htmlHelper.ViewContext.ViewData), htmlHelper.ViewContext);
                mockValidator.Setup(v => v.GetClientValidationRules())
                .Returns(expectedValidationRules);
                Mock <ModelValidatorProvider> mockValidatorProvider = new Mock <ModelValidatorProvider>();
                mockValidatorProvider.Setup(vp => vp.GetValidators(It.IsAny <ModelMetadata>(), It.IsAny <ControllerContext>()))
                .Returns(new[] { mockValidator.Object });
                ModelValidatorProviders.Providers.Add(mockValidatorProvider.Object);

                // Act
                MvcHtmlString html = htmlHelper.ValidationMessage("baz"); // 'baz' is valid

                // Assert
                Assert.Equal(@"<span class=""field-validation-valid"" data-valmsg-for=""baz"" data-valmsg-replace=""true""></span>", html.ToHtmlString());
            }
            finally
            {
                ModelValidatorProviders.Providers.Clear();
                foreach (var provider in originalProviders)
                {
                    ModelValidatorProviders.Providers.Add(provider);
                }
            }
        }
        // Generates the validation message cells associated with form controls
        private static string ValidationCells(HtmlHelper helper, string prefix, IEnumerable <string> extraColumns)
        {
            StringBuilder html = new StringBuilder();

            foreach (string column in extraColumns)
            {
                string        name       = String.Format("{0}.{1}", prefix, column);
                MvcHtmlString validation = helper.ValidationMessage(name);
                TagBuilder    cell       = new TagBuilder("td");
                cell.InnerHtml = validation.ToString();
                html.Append(cell.ToString());
            }
            return(html.ToString());
        }
Example #27
0
        public static string FieldTemplate(this HtmlHelper html, string id, string title, bool forCheckbox = false, string example = null, bool required = false, string description = null, string fieldName = null)
        {
            var label = html.QpLabel(html.UniqueId(id), title, !forCheckbox).ToString();

            if (!string.IsNullOrWhiteSpace(description))
            {
                label = $"{label} <span class='linkButton fieldDescription' data-field_description_text='{description}'>" + "<a href='javascript:void(0);'>" + "<span class='text'>(?)</span>" + "</a>" + "</span>";
            }

            if (required && !forCheckbox)
            {
                var star = new TagBuilder("span");
                star.MergeAttribute("class", "star");
                star.InnerHtml = "*";
                label          = $"{star} {label}";
            }

            var labelCell = new TagBuilder("dt");

            labelCell.AddCssClass(LabelClassName);
            labelCell.InnerHtml = forCheckbox ? string.Empty : label;

            var validatorWrapper = new TagBuilder("em");

            validatorWrapper.AddCssClass(ValidatorsClassName);

            var validator = html.ValidationMessage(id, new { id = html.UniqueId(id) + "_validator" });

            if (validator != null)
            {
                validatorWrapper.InnerHtml = validator.ToString().ProtectCurlyBrackets();
            }

            var exampleCode = string.IsNullOrEmpty(example)
                ? string.Empty
                : $"<em class=\"{DescriptionClassName}\">{example}</em>";

            var fieldCell = new TagBuilder("dd");

            fieldCell.AddCssClass(FieldClassName);
            fieldCell.InnerHtml = "{0}" + (forCheckbox ? " " + label : exampleCode) + validatorWrapper;
            fieldName           = fieldName?.Replace("\"", "") ?? "";
            if (!string.IsNullOrEmpty(fieldName))
            {
                fieldName = $"data-field_name=\"{fieldName}\"";
            }

            return($"<dl class=\"{RowClassName}\" data-field_form_name=\"{id}\" {fieldName}>{labelCell}{fieldCell}</dl>");
        }
        public static string RenderRadioButton(HtmlHelper html, BootstrapRadioButtonModel model)
        {
            if (model.tooltipConfiguration != null) model.htmlAttributes.MergeHtmlAttributes(model.tooltipConfiguration.ToDictionary());

            model.htmlAttributes.MergeHtmlAttributes(html.GetUnobtrusiveValidationAttributes(model.htmlFieldName, model.metadata));
            if (!string.IsNullOrEmpty(model.id)) model.htmlAttributes.AddOrReplace("id", model.id);

            string validationMessage = "";
            if (model.displayValidationMessage)
            {
                string validation = html.ValidationMessage(model.htmlFieldName).ToHtmlString();
                validationMessage = new BootstrapHelpText(validation, model.validationMessageStyle).ToHtmlString();
            }
            return html.RadioButton(model.htmlFieldName, model.value, model.isChecked, model.htmlAttributes.FormatHtmlAttributes()).ToHtmlString() + validationMessage;
        }
        public static string RenderFile(HtmlHelper html, BootstrapFileModel model)
        {
            if (model == null || string.IsNullOrEmpty(model.htmlFieldName)) return null;

            string validationMessage = "";
            if (model.displayValidationMessage)
            {
                string validation = html.ValidationMessage(model.htmlFieldName).ToHtmlString();
                validationMessage = new BootstrapHelpText(validation, model.validationMessageStyle).ToHtmlString();
            }
            if (model.tooltipConfiguration != null) model.htmlAttributes.AddRange(model.tooltipConfiguration.ToDictionary());
            var mergedHtmlAttrs = model.htmlAttributes.FormatHtmlAttributes().AddOrReplace("type", "File");
            if (!string.IsNullOrEmpty(model.id)) mergedHtmlAttrs.AddOrReplace("id", model.id);
            return html.TextBox(model.htmlFieldName, null, mergedHtmlAttrs).ToHtmlString() + validationMessage;
        }
Example #30
0
        /// <summary>
        /// Create full captcha
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="text"></param>
        /// <param name="inputText"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        internal static MvcHtmlString GenerateFullCaptcha(HtmlHelper htmlHelper, string text, string inputText, int length)
        {
            var encryptorModel = GetEncryptorModel();
            var captchaText    = RandomText.Generate(length);
            var encryptText    = GetEncryption().Encrypt(captchaText, encryptorModel.Password, encryptorModel.Salt);
            var urlHelper      = new UrlHelper(htmlHelper.ViewContext.RequestContext);
            var url            = urlHelper.Action("Create", "CaptchaImage", new { encryptText });
            var ajax           = new AjaxHelper(htmlHelper.ViewContext, htmlHelper.ViewDataContainer);
            var refresh        = ajax.ActionLink(text, "NewCaptcha", "CaptchaImage", new { l = length },
                                                 new AjaxOptions {
                UpdateTargetId = "CaptchaDeText", OnSuccess = "Success"
            });
            string tgs = "<div style=\"float: left; margin-top: 5px;\">" + refresh.ToHtmlString() + " <br/>" + inputText + "<br/>" +
                         htmlHelper.TextBox("CaptchaInputText", "", new { data_val_required = "*", data_val = "true", data_val_length_min = "5", data_val_length_max = "5", data_val_length = "*" }) +
                         htmlHelper.ValidationMessage("CaptchaInputText") + "</div>";

            return(MvcHtmlString.Create(tgs + string.Format(CaptchaFormat, url, htmlHelper.Hidden("CaptchaDeText", encryptText))));
        }
Example #31
0
        /// <summary>
        /// Renders html depends on model's type (i.e. textbox, radion buttons)
        /// </summary>
        /// <param name="html">The HTML.</param>
        /// <param name="model">The model.</param>
        /// <param name="collection">The collection.</param>
        /// <returns></returns>
        public static MvcHtmlString FormElementRenderer(this HtmlHelper html, FormElement model, FormCollection collection)
        {
            var builder = new StringBuilder();

            var elementName  = String.Format(FormElementNameFormat, model.Type, model.Id);
            var elementValue = String.Empty;

            if (collection != null && collection[elementName] != null)
            {
                elementValue = collection[elementName];
            }

            builder.Append(RenderElementByType(html, model, elementName, elementValue));
            builder.Append("<br/>");
            builder.Append(html.ValidationMessage(elementName));

            return(MvcHtmlString.Create(builder.ToString()));
        }
 public static MvcHtmlString ValidationMessage(
     this HtmlHelper htmlHelper,
     string modelName,
     string validationMessage = null,
     string cssClass          = null,
     string dir   = null,
     string id    = null,
     string lang  = null,
     string style = null,
     string title = null
     )
 {
     return(htmlHelper.ValidationMessage(
                modelName,
                validationMessage,
                SpanAttributes(cssClass, dir, id, lang, style, title)
                ));
 }
Example #33
0
        public static MvcHtmlString AutocompleteDescription(this HtmlHelper helper, string name,
                                                            object htmlAttributes = null, string html = null)
        {
            var span = new TagBuilder("span");

            span.Attributes.Add("data-ac-msg-for", name);

            if (htmlAttributes != null)
            {
                span.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes), true);
            }

            if (html != null)
            {
                span.InnerHtml = html;
            }

            return(MvcHtmlString.Create(span.ToString(TagRenderMode.Normal) + helper.ValidationMessage(name)));
        }
Example #34
0
        public static MvcHtmlString ProfileElementRenderer(this HtmlHelper html, ProfileElement element, FormCollection collection)
        {
            var builder = new StringBuilder();

            var elementName  = String.Format(ElementNameFormat, (ElementType)element.Type, element.Id);
            var elementValue = String.Empty;

            if (collection != null && collection[elementName] != null)
            {
                elementValue = collection[elementName];
            }

            builder.Append(html.Label(elementName, element.Title));
            builder.Append("<br/>");
            builder.Append(ElementTypeUtility.RenderElementType(html, (ElementType)element.Type, elementName,
                                                                elementValue, element.ElementValues));
            builder.Append(html.ValidationMessage(elementName));

            return(MvcHtmlString.Create(builder.ToString()));
        }
        public static string RenderReadOnly(HtmlHelper html, BootstrapReadOnlyModel model, bool isPassword)
        {
            var combinedHtml = "{0}{1}{2}";

            model.htmlAttributes.MergeHtmlAttributes(html.GetUnobtrusiveValidationAttributes(model.htmlFieldName, model.metadata));

            if (!string.IsNullOrEmpty(model.id)) model.htmlAttributes.Add("id", model.id);
            if (model.tooltipConfiguration != null) model.htmlAttributes.MergeHtmlAttributes(model.tooltipConfiguration.ToDictionary());
            if (model.tooltip != null) model.htmlAttributes.MergeHtmlAttributes(model.tooltip.ToDictionary());
            // assign placeholder class
            if (!string.IsNullOrEmpty(model.placeholder)) model.htmlAttributes.Add("placeholder", model.placeholder);
            // build html for input

            string input = html.Hidden(model.htmlFieldName, model.value).ToHtmlString();

            if (model.value != null && model.value.GetType().IsEnum)
            {
                input =  input + ((Enum)model.value).GetEnumDescription();
            }
            else
            {
                input = input + html.Encode(model.value);

            }

            // account for appendString, prependString, and AppendButtons
            if (!string.IsNullOrEmpty(model.prependString) ||
                !string.IsNullOrEmpty(model.appendString) ||
                model.prependButtons.Any() ||
                model.appendButtons.Any() ||
                model.iconPrepend != Icons._not_set ||
                model.iconAppend != Icons._not_set ||
                !string.IsNullOrEmpty(model.iconPrependCustomClass) ||
                !string.IsNullOrEmpty(model.iconAppendCustomClass))
            {
                var appendPrependContainer = new TagBuilder("div");
                var addOnPrependString = "";
                var addOnAppendString = "";
                var addOnPrependButtons = "";
                var addOnAppendButtons = "";
                var addOnPrependIcon = "";
                var addOnAppendIcon = "";

                var addOn = new TagBuilder("span");
                addOn.AddCssClass("add-on");
                if (!string.IsNullOrEmpty(model.prependString))
                {
                    appendPrependContainer.AddOrMergeCssClass("input-prepend");
                    addOn.InnerHtml = model.prependString;
                    addOnPrependString = addOn.ToString();
                }
                if (!string.IsNullOrEmpty(model.appendString))
                {
                    appendPrependContainer.AddOrMergeCssClass("input-append");
                    addOn.InnerHtml = model.appendString;
                    addOnAppendString = addOn.ToString();
                }
                if (model.prependButtons.Count > 0)
                {
                    appendPrependContainer.AddOrMergeCssClass("input-prepend");
                    model.prependButtons.ForEach(x => addOnPrependButtons += x.ToHtmlString());
                }
                if (model.appendButtons.Count > 0)
                {
                    appendPrependContainer.AddOrMergeCssClass("input-append");
                    model.appendButtons.ForEach(x => addOnAppendButtons += x.ToHtmlString());
                }
                if (model.iconPrepend != Icons._not_set)
                {
                    appendPrependContainer.AddOrMergeCssClass("input-prepend");
                    addOn.InnerHtml = new BootstrapIcon(model.iconPrepend, model.iconPrependIsWhite).ToHtmlString();
                    addOnPrependIcon = addOn.ToString();
                }
                if (model.iconAppend != Icons._not_set)
                {
                    appendPrependContainer.AddOrMergeCssClass("input-append");
                    addOn.InnerHtml = new BootstrapIcon(model.iconAppend, model.iconAppendIsWhite).ToHtmlString();
                    addOnAppendIcon = addOn.ToString();
                }
                if (!string.IsNullOrEmpty(model.iconPrependCustomClass))
                {
                    appendPrependContainer.AddOrMergeCssClass("input-prepend");
                    var i = new TagBuilder("i");
                    i.AddCssClass(model.iconPrependCustomClass);
                    addOn.InnerHtml = i.ToString(TagRenderMode.Normal);
                    addOnPrependIcon = addOn.ToString();
                }
                if (!string.IsNullOrEmpty(model.iconAppendCustomClass))
                {
                    appendPrependContainer.AddOrMergeCssClass("input-append");
                    var i = new TagBuilder("i");
                    i.AddCssClass(model.iconAppendCustomClass);
                    addOn.InnerHtml = i.ToString(TagRenderMode.Normal);
                    addOnAppendIcon = addOn.ToString();
                }

                appendPrependContainer.InnerHtml = addOnPrependButtons + addOnPrependIcon + addOnPrependString + "{0}" + addOnAppendString + addOnAppendIcon + addOnAppendButtons;
                combinedHtml = appendPrependContainer.ToString(TagRenderMode.Normal) + "{1}{2}";
            }

            var helpText = model.helpText != null ? model.helpText.ToHtmlString() : string.Empty;
            var validationMessage = "";
            if (model.displayValidationMessage && html.ValidationMessage(model.htmlFieldName) != null )
            {
                var validation = html.ValidationMessage(model.htmlFieldName).ToHtmlString();
                validationMessage = new BootstrapHelpText(validation, model.validationMessageStyle).ToHtmlString();
            }

            return MvcHtmlString.Create(string.Format(combinedHtml, input, helpText, validationMessage)).ToString();
        }
        public static string RenderInputListContainer(
            HtmlHelper html,
            string htmlFieldName,
            List<string> inputs,
            int? numberOfColumns,
            bool displayInColumnsCondition,
            int columnPixelWidth,
            bool displayInlineBlock,
            int marginRightPx,
            bool displayValidationMessage,
            HelpTextStyle validationMessageStyle
            )
        {
            TagBuilder container = new TagBuilder("div");
            container.AddCssClass("input-list-container");
            if (displayValidationMessage)
            {
                container.AddCssStyle("display", "inline-block");
                container.AddCssStyle("vertical-align", "middle");
                container.AddCssStyle("margin-top", "4px");
            }

            if (numberOfColumns.HasValue && displayInColumnsCondition)
            {
                container.AddCssStyle("max-width", (columnPixelWidth * numberOfColumns).ToString() + "px");
                List<string> columnedInputs = new List<string>();
                TagBuilder columnDiv = new TagBuilder("div");
                columnDiv.AddCssClass("input-list-column");
                columnDiv.AddCssStyle("width", columnPixelWidth.ToString() + "px");
                columnDiv.AddCssStyle("display", "inline-block");
                foreach (var input in inputs)
                {
                    columnDiv.InnerHtml = input;
                    columnedInputs.Add(columnDiv.ToString());
                }
                inputs = columnedInputs;
            }

            if (displayInlineBlock)
            {
                List<string> columnedInputs = new List<string>();
                TagBuilder columnDiv = new TagBuilder("div");
                columnDiv.AddCssClass("input-list-inline");
                columnDiv.AddCssStyle("display", "inline-block");
                columnDiv.AddCssStyle("margin-right", marginRightPx.ToString() + "px");
                foreach (var input in inputs)
                {
                    columnDiv.InnerHtml = input;
                    columnedInputs.Add(columnDiv.ToString());
                }
                inputs = columnedInputs;
            }

            string inputsCombined = string.Empty;
            inputs.ForEach(c => inputsCombined += c);
            container.InnerHtml = inputsCombined;

            string validationMessage = "";
            if (displayValidationMessage)
            {
                string validation = html.ValidationMessage(htmlFieldName).ToHtmlString();
                validationMessage = new BootstrapHelpText(validation, validationMessageStyle).ToHtmlString();
            }

            return container.ToString(TagRenderMode.Normal) + validationMessage;
        }
        public static string RenderTextBox(HtmlHelper html, BootstrapTextBoxModel model, bool isPassword)
        {
            if (model == null || string.IsNullOrEmpty(model.htmlFieldName)) return null;

            string combinedHtml = "{0}{1}{2}";

            if (!string.IsNullOrEmpty(model.id)) model.htmlAttributes.Add("id", model.id);
            if (model.tooltipConfiguration != null) model.htmlAttributes.AddRange(model.tooltipConfiguration.ToDictionary());
            // assign placeholder class
            if (!string.IsNullOrEmpty(model.placeholder)) model.htmlAttributes.Add("placeholder", model.placeholder);
            // assign size class
            model.htmlAttributes.AddOrMergeCssClass("class", BootstrapHelper.GetClassForInputSize(model.size));
            // build html for input
            var input = isPassword
                ? html.Password(model.htmlFieldName, model.value, model.htmlAttributes.FormatHtmlAttributes()).ToHtmlString()
                : html.TextBox(model.htmlFieldName, model.value, model.format, model.htmlAttributes.FormatHtmlAttributes()).ToHtmlString();

            // account for appendString, prependString, and AppendButtons
            if (!string.IsNullOrEmpty(model.prependString) ||
                !string.IsNullOrEmpty(model.appendString) ||
                model.prependButtons.Any() ||
                model.appendButtons.Any() ||
                model.iconPrepend != Icons._not_set ||
                model.iconAppend != Icons._not_set ||
                !string.IsNullOrEmpty(model.iconPrependCustomClass) ||
                !string.IsNullOrEmpty(model.iconAppendCustomClass))
            {
                TagBuilder appendPrependContainer = new TagBuilder("div");
                string addOnPrependString = "";
                string addOnAppendString = "";
                string addOnPrependButtons = "";
                string addOnAppendButtons = "";
                string addOnPrependIcon = "";
                string addOnAppendIcon = "";

                TagBuilder addOn = new TagBuilder("span");
                addOn.AddCssClass("add-on");
                if (!string.IsNullOrEmpty(model.prependString))
                {
                    appendPrependContainer.AddOrMergeCssClass("input-prepend");
                    addOn.InnerHtml = model.prependString;
                    addOnPrependString = addOn.ToString();
                }
                if (!string.IsNullOrEmpty(model.appendString))
                {
                    appendPrependContainer.AddOrMergeCssClass("input-append");
                    addOn.InnerHtml = model.appendString;
                    addOnAppendString = addOn.ToString();
                }
                if (model.prependButtons.Count() > 0)
                {
                    appendPrependContainer.AddOrMergeCssClass("input-prepend");
                    model.prependButtons.ForEach(x => addOnPrependButtons += x.ToHtmlString());
                }
                if (model.appendButtons.Count() > 0)
                {
                    appendPrependContainer.AddOrMergeCssClass("input-append");
                    model.appendButtons.ForEach(x => addOnAppendButtons += x.ToHtmlString());
                }
                if (model.iconPrepend != Icons._not_set)
                {
                    appendPrependContainer.AddOrMergeCssClass("input-prepend");
                    addOn.InnerHtml = new BootstrapIcon(model.iconPrepend, model.iconPrependIsWhite).ToHtmlString();
                    addOnPrependIcon = addOn.ToString();
                }
                if (model.iconAppend != Icons._not_set)
                {
                    appendPrependContainer.AddOrMergeCssClass("input-append");
                    addOn.InnerHtml = new BootstrapIcon(model.iconAppend, model.iconAppendIsWhite).ToHtmlString();
                    addOnAppendIcon = addOn.ToString();
                }
                if (!string.IsNullOrEmpty(model.iconPrependCustomClass))
                {
                    appendPrependContainer.AddOrMergeCssClass("input-prepend");
                    var i = new TagBuilder("i");
                    i.AddCssClass(model.iconPrependCustomClass);
                    addOn.InnerHtml = i.ToString(TagRenderMode.Normal);
                    addOnPrependIcon = addOn.ToString();
                }
                if (!string.IsNullOrEmpty(model.iconAppendCustomClass))
                {
                    appendPrependContainer.AddOrMergeCssClass("input-append");
                    var i = new TagBuilder("i");
                    i.AddCssClass(model.iconAppendCustomClass);
                    addOn.InnerHtml = i.ToString(TagRenderMode.Normal);
                    addOnAppendIcon = addOn.ToString();
                }

                appendPrependContainer.InnerHtml = addOnPrependButtons + addOnPrependIcon + addOnPrependString + "{0}" + addOnAppendString + addOnAppendIcon + addOnAppendButtons;
                combinedHtml = appendPrependContainer.ToString(TagRenderMode.Normal) + "{1}{2}";
            }

            string helpText = model.helpText != null ? model.helpText.ToHtmlString() : string.Empty;
            string validationMessage = "";
            if(model.displayValidationMessage)
            {
                string validation = html.ValidationMessage(model.htmlFieldName).ToHtmlString();
                validationMessage = new BootstrapHelpText(validation, model.validationMessageStyle).ToHtmlString();
            }

            return MvcHtmlString.Create(string.Format(combinedHtml, input, validationMessage, helpText)).ToString();
        }
Example #38
0
 public override MvcHtmlString ProcessTag(HtmlHelper htmlHelper, IContext context, string content, object[] parms)
 {
     return htmlHelper.ValidationMessage(parms[0].ToString());
 }
Example #39
0
 /// <summary>
 /// Create full captcha
 /// </summary>
 /// <param name="htmlHelper"></param>
 /// <param name="text"></param>
 /// <param name="inputText"></param>
 /// <param name="length"></param>
 /// <returns></returns>
 internal static MvcHtmlString GenerateFullCaptcha(HtmlHelper htmlHelper, string text, string inputText, int length)
 {
     var encryptorModel = GetEncryptorModel();
     var captchaText = RandomText.Generate(length);
     var encryptText = GetEncryption().Encrypt(captchaText, encryptorModel.Password, encryptorModel.Salt);
     var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
     var url = urlHelper.Action("Create", "CaptchaImage", new { encryptText });
     var ajax = new AjaxHelper(htmlHelper.ViewContext, htmlHelper.ViewDataContainer);
     var refresh = ajax.ActionLink(text, "NewCaptcha", "CaptchaImage", new { l = length },
                                                                 new AjaxOptions { UpdateTargetId = "CaptchaDeText", OnSuccess = "Success" });
     string tgs = "<div style=\"float: left; margin-top: 5px;\">" + refresh.ToHtmlString() + " <br/>" + inputText + "<br/>" +
         htmlHelper.TextBox("CaptchaInputText", "", new { data_val_required = "*", data_val = "true", data_val_length_min = "5", data_val_length_max = "5", data_val_length = "*" }) +
         htmlHelper.ValidationMessage("CaptchaInputText") + "</div>";
     return MvcHtmlString.Create(tgs + string.Format(CaptchaFormat, url, htmlHelper.Hidden("CaptchaDeText", encryptText)));
 }
        internal static string ObjectTemplate(HtmlHelper html, TemplateHelpers.TemplateHelperDelegate templateHelper)
        {
            ViewDataDictionary viewData = html.ViewContext.ViewData;
            TemplateInfo templateInfo = viewData.TemplateInfo;
            ModelMetadata modelMetadata = viewData.ModelMetadata;
            StringBuilder builder = new StringBuilder();

            if (templateInfo.TemplateDepth > 1)
            {
                // DDB #224751
                return modelMetadata.Model == null ? modelMetadata.NullDisplayText : modelMetadata.SimpleDisplayText;
            }

            foreach (ModelMetadata propertyMetadata in modelMetadata.Properties.Where(pm => ShouldShow(pm, templateInfo)))
            {
                if (!propertyMetadata.HideSurroundingHtml)
                {
                    string label = LabelExtensions.LabelHelper(html, propertyMetadata, propertyMetadata.PropertyName).ToHtmlString();
                    if (!String.IsNullOrEmpty(label))
                    {
                        builder.AppendFormat(CultureInfo.InvariantCulture, "<div class=\"editor-label\">{0}</div>\r\n", label);
                    }

                    builder.Append("<div class=\"editor-field\">");
                }

                builder.Append(templateHelper(html, propertyMetadata, propertyMetadata.PropertyName, null /* templateName */, DataBoundControlMode.Edit, null /* additionalViewData */));

                if (!propertyMetadata.HideSurroundingHtml)
                {
                    builder.Append(" ");
                    builder.Append(html.ValidationMessage(propertyMetadata.PropertyName));
                    builder.Append("</div>\r\n");
                }
            }

            return builder.ToString();
        }
        public static string RenderSelectElement(HtmlHelper html, BootstrapSelectElementModel model, BootstrapInputType inputType)
        {
            if (model == null || string.IsNullOrEmpty(model.htmlFieldName) || model.selectList == null) return null;

            string combinedHtml = "{0}{1}{2}";
            if (model.selectedValue != null)
            {
                foreach (var item in model.selectList)
                {
                    if (item.Value == model.selectedValue.ToString())
                        item.Selected = true;
                }
            }

            model.htmlAttributes.AddRange(html.GetUnobtrusiveValidationAttributes(model.htmlFieldName, model.metadata));
            if (model.tooltipConfiguration != null) model.htmlAttributes.AddRange(model.tooltipConfiguration.ToDictionary());
            if (!string.IsNullOrEmpty(model.id)) model.htmlAttributes.AddOrReplace("id", model.id);

            // assign size class
            model.htmlAttributes.AddOrMergeCssClass("class", BootstrapHelper.GetClassForInputSize(model.size));

            // build html for input
            string input = string.Empty;

            if(inputType == BootstrapInputType.DropDownList)
                input = html.DropDownList(model.htmlFieldName, model.selectList, model.optionLabel, model.htmlAttributes.FormatHtmlAttributes()).ToHtmlString();

            if(inputType == BootstrapInputType.ListBox)
                input = html.ListBox(model.htmlFieldName, model.selectList, model.htmlAttributes.FormatHtmlAttributes()).ToHtmlString();

            // account for appendString, prependString, and AppendButtons
            TagBuilder appendPrependContainer = new TagBuilder("div");
            if (!string.IsNullOrEmpty(model.prependString) | !string.IsNullOrEmpty(model.appendString) | model.appendButtons.Count() > 0)
            {
                string addOnPrependString = "";
                string addOnAppendString = "";
                string addOnPrependButtons = "";
                string addOnAppendButtons = "";

                TagBuilder addOn = new TagBuilder("span");
                addOn.AddCssClass("add-on");
                if (!string.IsNullOrEmpty(model.prependString))
                {
                    appendPrependContainer.AddOrMergeCssClass("input-prepend");
                    addOn.InnerHtml = model.prependString;
                    addOnPrependString = addOn.ToString();
                }
                if (!string.IsNullOrEmpty(model.appendString))
                {
                    appendPrependContainer.AddOrMergeCssClass("input-append");
                    addOn.InnerHtml = model.appendString;
                    addOnAppendString = addOn.ToString();
                }
                if (model.appendButtons.Count() > 0)
                {
                    appendPrependContainer.AddOrMergeCssClass("input-append");
                    ((List<BootstrapButton>)model.appendButtons).ForEach(x => addOnAppendButtons += x.ToHtmlString());
                }
                if (model.prependButtons.Count() > 0)
                {
                    appendPrependContainer.AddOrMergeCssClass("input-append");
                    ((List<BootstrapButton>)model.prependButtons).ForEach(x => addOnPrependButtons += x.ToHtmlString());
                }

                appendPrependContainer.InnerHtml = addOnPrependButtons + addOnPrependString + "{0}" + addOnAppendString + addOnAppendButtons;
                combinedHtml = appendPrependContainer.ToString(TagRenderMode.Normal) + "{1}{2}";
            }

            string helpText = model.helpText != null ? model.helpText.ToHtmlString() : string.Empty;
            string validationMessage = "";
            if (model.displayValidationMessage)
            {
                string validation = html.ValidationMessage((string)model.htmlFieldName).ToHtmlString();
                validationMessage = new BootstrapHelpText(validation, model.validationMessageStyle).ToHtmlString();
            }

            return MvcHtmlString.Create(string.Format(combinedHtml, input, validationMessage, helpText)).ToString();
        }
        public static string RenderRadioButtonTrueFalse(HtmlHelper html, BootstrapRadioButtonTrueFalseModel model)
        {
            TagBuilder inputsContainer = new TagBuilder("div");
            inputsContainer.AddCssClass("container-radio-true-false");
            inputsContainer.AddCssStyle("display", "inline-block");
            inputsContainer.AddCssStyle("margin-top", "4px");
            if (model.tooltipConfiguration != null) inputsContainer.MergeAttributes(model.tooltipConfiguration.ToDictionary());

            string fullHtmlFieldName = html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(model.htmlFieldName);

            bool trueValueIsSelected = false;
            bool falseValueIsSelected = false;
            if (model.metadata.Model != null)
            {
                trueValueIsSelected = model.inputTrueValue.ToString() == model.metadata.Model.ToString();
                falseValueIsSelected = model.inputTrueValue.ToString() != model.metadata.Model.ToString();
            }

            var inputTrue = Renderer.RenderLabel(html, new BootstrapLabelModel
            {
                htmlFieldName = model.htmlFieldName,
                labelText = model.labelTrueText,
                metadata = model.metadata,
                htmlAttributes = model.htmlAttributesLabelTrue,
                showRequiredStar = false,
                innerInputType = BootstrapInputType.Radio,
                innerInputModel = new BootstrapRadioButtonModel
                {
                    htmlFieldName = model.htmlFieldName,
                    value = model.inputTrueValue,
                    metadata = model.metadata,
                    isChecked = trueValueIsSelected,
                    htmlAttributes = model.htmlAttributesInputTrue.AddOrReplace("id", fullHtmlFieldName.FormatForMvcInputId() + "_t")
                }
            });

            var inputFalse = Renderer.RenderLabel(html, new BootstrapLabelModel
            {
                htmlFieldName = model.htmlFieldName,
                labelText = model.labelFalseText,
                metadata = model.metadata,
                htmlAttributes = model.htmlAttributesLabelFalse,
                showRequiredStar = false,
                innerInputType = BootstrapInputType.Radio,
                innerInputModel = new BootstrapRadioButtonModel
                {
                    htmlFieldName = model.htmlFieldName,
                    value = model.inputFalseValue,
                    metadata = model.metadata,
                    isChecked = falseValueIsSelected,
                    htmlAttributes = model.htmlAttributesInputFalse.AddOrReplace("id", fullHtmlFieldName.FormatForMvcInputId() + "_f")
                }
            });

            string helpText = model.helpText != null ? model.helpText.ToHtmlString() : string.Empty;
            string validationMessage = "";
            if (model.displayValidationMessage)
            {
                string validation = html.ValidationMessage(model.htmlFieldName).ToHtmlString();
                validationMessage = new BootstrapHelpText(validation, model.validationMessageStyle).ToHtmlString();
            }

            inputsContainer.InnerHtml = inputTrue + inputFalse;
            return inputsContainer.ToString() + validationMessage + helpText;
        }