Example #1
0
        public void ReplaceValidationSummaryProperty() {
            // Arrange
            FormContext context = new FormContext();

            // Act & Assert
            MemberHelper.TestBooleanProperty(context, "ReplaceValidationSummary", false, false);
        }
        public void ClientValidationFunctionProperty() {
            // Arrange
            FormContext context = new FormContext();

            // Act & assert
            MemberHelper.TestStringProperty(context, "ClientValidationFunction", "EnableClientValidation", false /* testDefaultValue */, true /* allowNullAndEmpty */, "EnableClientValidation" /* nullAndEmptyReturnValue */);
        }
        // Only render attributes if unobtrusive client-side validation is enabled, and then only if we've
        // never rendered validation for a field with this name in this form. Also, if there's no form context,
        // then we can't render the attributes (we'd have no <form> to attach them to).
        public IDictionary <string, object> GetUnobtrusiveValidationAttributes(string name, ModelMetadata metadata)
        {
            Dictionary <string, object> results = new Dictionary <string, object>();

            // The ordering of these 3 checks (and the early exits) is for performance reasons.
            if (!ViewContext.UnobtrusiveJavaScriptEnabled)
            {
                return(results);
            }

            FormContext formContext = ViewContext.GetFormContextForClientValidation();

            if (formContext == null)
            {
                return(results);
            }

            string fullName = ViewData.TemplateInfo.GetFullHtmlFieldName(name);

            if (formContext.RenderedField(fullName))
            {
                return(results);
            }

            formContext.RenderedField(fullName, true);

            IEnumerable <ModelClientValidationRule> clientRules = ClientValidationRuleFactory(name, metadata);

            UnobtrusiveValidationAttributesGenerator.GetValidationAttributes(clientRules, results);

            return(results);
        }
        public TemplateScript(ViewContext viewContext, TextWriter write, FormContext originalFormContextr)
        {
            _viewContext = viewContext;
            _originalFormContext = originalFormContextr;

            Initialize(write);

            _writer.Write(ScriptTag.Rendar(TagRenderMode.StartTag));
        }
        /// <summary>
        /// Initializes evaluatedValueString new instance of the <see cref="FormGroupHelper"/> class.
        /// </summary>
        /// <param name="htmlHelper">The HTML helper.</param>
        /// <param name="tagBuilder">The tag builder.</param>
        public FormGroupHelper(HtmlHelper htmlHelper, TagBuilder tagBuilder)
            : base(htmlHelper, tagBuilder, false, false)
        {
            _originalFormContext = ViewContext.FormContext;
            ViewContext.FormContext = new FormContext();

            string id;
            if (tagBuilder.Attributes.TryGetValue("id", out id))
                htmlHelper.ViewContext.FormContext.FormId = id;
        }
Example #6
0
        public void FieldValidatorsProperty() {
            // Arrange
            FormContext context = new FormContext();

            // Act
            IDictionary<String, FieldValidationMetadata> fieldValidators = context.FieldValidators;

            // Assert
            Assert.IsNotNull(fieldValidators);
            Assert.AreEqual(0, fieldValidators.Count);
        }
Example #7
0
        // Only render attributes if unobtrusive client-side validation is enabled, and then only if we've
        // never rendered validation for a field with this name in this form. Also, if there's no form context,
        // then we can't render the attributes (we'd have no <form> to attach them to).
        public IDictionary <string, object> GetUnobtrusiveValidationAttributes(string name, ModelMetadata metadata)
        {
            Dictionary <string, object> results = new Dictionary <string, object>();

            // The ordering of these 3 checks (and the early exits) is for performance reasons.
            if (!ViewContext.UnobtrusiveJavaScriptEnabled)
            {
                return(results);
            }

            FormContext formContext = ViewContext.GetFormContextForClientValidation();

            if (formContext == null)
            {
                return(results);
            }

            string fullName = ViewData.TemplateInfo.GetFullHtmlFieldName(name);

            if (formContext.RenderedField(fullName))
            {
                return(results);
            }

            formContext.RenderedField(fullName, true);

            IEnumerable <ModelClientValidationRule> clientRules = ClientValidationRuleFactory(name, metadata);
            bool renderedRules = false;

            foreach (ModelClientValidationRule rule in clientRules)
            {
                renderedRules = true;
                string ruleName = "data-val-" + rule.ValidationType;

                ValidateUnobtrusiveValidationRule(rule, results, ruleName);

                results.Add(ruleName, HttpUtility.HtmlEncode(rule.ErrorMessage ?? String.Empty));
                ruleName += "-";

                foreach (var kvp in rule.ValidationParameters)
                {
                    results.Add(ruleName + kvp.Key, kvp.Value ?? String.Empty);
                }
            }

            if (renderedRules)
            {
                results.Add("data-val", "true");
            }

            return(results);
        }
        public void ConstructorCopiesFormContextReferenceFromOriginalViewContext() {
            // Arrange
            FormContext formContext = new FormContext();
            ViewContext originalViewContext = new ViewContext() {
                FormContext = formContext
            };

            // Act
            ViewContext newViewContext = new ViewContext(originalViewContext, new Mock<IView>().Object, new ViewDataDictionary(), new TempDataDictionary());

            // Assert
            Assert.AreEqual(formContext, newViewContext.FormContext, "FormContext should have been propagated between ViewContexts.");
        }
        public void GetValidationMetadataForField_NoCreate_ReturnsMetadataIfFound() {
            // Arrange
            FormContext context = new FormContext();
            FieldValidationMetadata metadata = new FieldValidationMetadata();
            context.FieldValidators["fieldName"] = metadata;

            // Act
            FieldValidationMetadata result = context.GetValidationMetadataForField("fieldName");

            // Assert
            Assert.IsNotNull(result);
            Assert.AreEqual(metadata, result);
        }
Example #10
0
        public BootstrapPanel(ViewContext viewContext, string title)
        {
            if (viewContext == null)
            {
                throw new ArgumentNullException("viewContext");
            }
            _viewContext = viewContext;
            _writer = viewContext.Writer;
            _originalFormContext = viewContext.FormContext;
            viewContext.FormContext = new FormContext();

            Begin(title);
        }
Example #11
0
        public void GetValidationMetadataForField_Create_CreatesNewMetadataIfNotFound() {
            // Arrange
            FormContext context = new FormContext();

            // Act
            FieldValidationMetadata result = context.GetValidationMetadataForField("fieldName", true /* createIfNotFound */);

            // Assert
            Assert.IsNotNull(result);
            Assert.AreEqual("fieldName", result.FieldName);

            Assert.AreEqual(1, context.FieldValidators.Count, "New metadata should have been added to FieldValidators.");
            Assert.AreEqual(result, context.FieldValidators["fieldName"]);
        }
Example #12
0
        public void OutputClientValidation()
        {
            FormContext formContext = GetFormContextForClientValidation();

            if (formContext == null || UnobtrusiveJavaScriptEnabled)
            {
                return; // do nothing
            }

            string scriptWithCorrectNewLines = ClientValidationScript.Replace("\r\n", Environment.NewLine);
            string validationJson            = formContext.GetJsonValidationMetadata();
            string formatted = String.Format(CultureInfo.InvariantCulture, scriptWithCorrectNewLines, validationJson);

            Writer.Write(formatted);
        }
        public void BeginFormSetsAndRestoresFormContext() {
            // Arrange
            AjaxHelper ajaxHelper = GetAjaxHelper();

            FormContext originalContext = new FormContext();
            ajaxHelper.ViewContext.FormContext = originalContext;

            // Act & assert - push
            MvcForm theForm = ajaxHelper.BeginForm(new AjaxOptions());
            Assert.IsNotNull(ajaxHelper.ViewContext.FormContext);
            Assert.AreNotEqual(originalContext, ajaxHelper.ViewContext.FormContext, "FormContext should have been set to a new instance.");

            // Act & assert - pop
            theForm.Dispose();
            Assert.AreEqual(originalContext, ajaxHelper.ViewContext.FormContext, "FormContext was not properly restored.");
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="HtmlContainer"/> class.
        /// </summary>
        /// <param name="viewContext">Context to write html</param>
        /// <param name="containerBegin">Container begin html</param>
        /// <param name="containerEnd">Container end html</param>
        public HtmlContainer(ViewContext viewContext, string containerBegin, string containerEnd)
        {
            if (viewContext == null)
            {
                throw new ArgumentNullException("viewContext");
            }

            this.containerBegin = containerBegin;
            this.containerEnd = containerEnd;
            this.viewContext = viewContext;
            this.writer = viewContext.Writer;
            this.originalFormContext = viewContext.FormContext;
            this.viewContext.FormContext = new FormContext();

            this.Begin();
        }
Example #15
0
        public void GetJsonValidationMetadata_ValidationSummary() {
            // Arrange
            FormContext context = new FormContext() { FormId = "theFormId", ValidationSummaryId = "validationSummary" };

            ModelClientValidationRule rule = new ModelClientValidationRule() { ValidationType = "ValidationType1", ErrorMessage = "Error Message" };
            rule.ValidationParameters["theParam"] = new { FirstName = "John", LastName = "Doe", Age = 32 };
            FieldValidationMetadata metadata = new FieldValidationMetadata() { FieldName = "theFieldName", ValidationMessageId = "theFieldName_ValidationMessage" };
            metadata.ValidationRules.Add(rule);
            context.FieldValidators["theFieldName"] = metadata;

            // Act
            string jsonMetadata = context.GetJsonValidationMetadata();

            // Assert
            string expected = @"{""Fields"":[{""FieldName"":""theFieldName"",""ReplaceValidationMessageContents"":false,""ValidationMessageId"":""theFieldName_ValidationMessage"",""ValidationRules"":[{""ErrorMessage"":""Error Message"",""ValidationParameters"":{""theParam"":{""FirstName"":""John"",""LastName"":""Doe"",""Age"":32}},""ValidationType"":""ValidationType1""}]}],""FormId"":""theFormId"",""ReplaceValidationSummary"":false,""ValidationSummaryId"":""validationSummary""}";
            Assert.AreEqual(expected, jsonMetadata);
        }
 public ActionResult AddMoreInfo(FormContext from)
 {
     return View();
 }
        /// <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)));
        }
Example #18
0
        private static string GetSummary(HtmlHelper htmlHelper)
        {
            var viewContext = htmlHelper.ViewContext;

            System.Web.Mvc.FormContext formContext = viewContext.ClientValidationEnabled ? viewContext.FormContext : null;

            if (htmlHelper.ViewData.ModelState.IsValid && formContext == null)
            {
                return(null);
            }

            var           modelState  = GetModelStateList(htmlHelper);
            StringBuilder listBuilder = new StringBuilder();

            foreach (var state in modelState)
            {
                foreach (var error in state.Value.Errors)
                {
                    string message = error.ErrorMessage;
                    if (!string.IsNullOrWhiteSpace(message))
                    {
                        listBuilder.Append("<li>");

                        string key = state.Key;
                        if (!string.IsNullOrWhiteSpace(key) && !message.Contains(key))
                        {
                            int lastDot = key.LastIndexOf('.');
                            if (lastDot != -1)
                            {
                                string suffix = key.Substring(lastDot + 1);
                                if (message.Contains(suffix))
                                {
                                    key = key.Substring(0, lastDot);
                                }
                            }
                            listBuilder.Append("<strong>");
                            listBuilder.Append(key.Replace('.', ' ').ToWords(true));
                            listBuilder.Append("</strong> ");
                        }

                        listBuilder.Append(message);
                        listBuilder.AppendLine("</li>");
                    }
                }
            }
            if (listBuilder.Length == 0)
            {
                if (viewContext.UnobtrusiveJavaScriptEnabled || formContext == null)
                {
                    return(null);
                }

                listBuilder.AppendLine("<li style=\"display:none\"></li>");
            }

            var listTag = new HtmlTagBuilder("ul")
            {
                InnerHtml = listBuilder.ToString()
            };
            var divBuilder = new HtmlTagBuilder("div");

            divBuilder.AddCssClass(htmlHelper.ViewData.ModelState.IsValid ? HtmlHelper.ValidationSummaryValidCssClassName : HtmlHelper.ValidationSummaryCssClassName);
            divBuilder.AddCssClass("alert alert-danger fade in");
            if (formContext != null)
            {
                if (viewContext.UnobtrusiveJavaScriptEnabled)
                {
                    divBuilder.MergeAttribute("data-valmsg-summary", "true");
                }
                else
                {
                    divBuilder.GenerateId("validationSummary");
                    formContext.ValidationSummaryId      = divBuilder.Attributes["id"];
                    formContext.ReplaceValidationSummary = true;
                }
            }
            divBuilder.InnerHtml = "<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;</button>"
                                   + listTag.ToString();

            return(divBuilder.ToString());
        }
        public void RenderedFieldIsFalseByDefault() {
            // Arrange
            var context = new FormContext();

            // Act
            bool result = context.RenderedField(Guid.NewGuid().ToString());

            // Assert
            Assert.IsFalse(result);
        }
        public void CanSetRenderedFieldToBeTrue() {
            // Arrange
            var context = new FormContext();
            var name = Guid.NewGuid().ToString();
            context.RenderedField(name, true);

            // Act
            bool result = context.RenderedField(name);

            // Assert
            Assert.IsTrue(result);
        }
Example #21
0
        public void GetValidationMetadataForFieldThrowsIfFieldNameIsNull() {
            // Arrange
            FormContext context = new FormContext();

            // Act & assert
            ExceptionHelper.ExpectArgumentExceptionNullOrEmpty(
                delegate {
                    context.GetValidationMetadataForField(null);
                }, "fieldName");
        }
Example #22
0
 public ActionResult LogOff(FormContext form)
 {
     HttpContext.SignOut();
     return RedirectToAction("Index", "Posts");
 }
Example #23
0
        public void GetValidationMetadataForField_NoCreate_ReturnsNullIfNotFound() {
            // Arrange
            FormContext context = new FormContext();

            // Act
            FieldValidationMetadata result = context.GetValidationMetadataForField("fieldName");

            // Assert
            Assert.IsNull(result);
        }
        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)));
        }