Ejemplo n.º 1
0
 public static IHtmlString BootstrapLabelFor(
     this HtmlHelper helper,
     string propertyName,
     string colMd)
 {
     return(LabelHelper(helper, ModelMetadata.FromStringExpression(propertyName, helper.ViewData), ExpressionHelper.GetExpressionText(propertyName),
                        "col-md-" + colMd + " control-label"));
     //return helper.Label(propertyName, new
     //{
     //    @class = "col-md-3 control-label"
     //});
 }
        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);
                }
            }
        }
Ejemplo n.º 3
0
        public void FromStringExpressionGuardClauses()
        {
            // Null expression throws
            Assert.ThrowsArgumentNull(
                () => ModelMetadata.FromStringExpression(null, new ViewDataDictionary()),
                "expression");

            // Null view data dictionary throws
            Assert.ThrowsArgumentNull(
                () => ModelMetadata.FromStringExpression("expression", null),
                "viewData");
        }
        public void Validate_AddsClientValidationMetadata()
        {
            var originalProviders = ModelValidatorProviders.Providers.ToArray();

            ModelValidatorProviders.Providers.Clear();

            try
            {
                // Arrange
                HtmlHelper  htmlHelper  = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());
                FormContext formContext = new FormContext()
                {
                    FormId = "form_id"
                };
                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
                htmlHelper.Validate("baz");

                // Assert
                Assert.NotNull(formContext.GetValidationMetadataForField("baz"));
                Assert.Equal(expectedValidationRules, formContext.FieldValidators["baz"].ValidationRules.ToArray());
            }
            finally
            {
                ModelValidatorProviders.Providers.Clear();
                foreach (var provider in originalProviders)
                {
                    ModelValidatorProviders.Providers.Add(provider);
                }
            }
        }
Ejemplo n.º 5
0
        public void TemplateHelperReturnsEmptyStringForAlreadyVisitedType()      // DDB #224750
        {
            HtmlHelper    html     = MakeHtmlHelper(new TemplateHelperModel());
            ModelMetadata metadata = ModelMetadata.FromStringExpression("MyProperty", html.ViewData);

            html.ViewData.TemplateInfo.VisitedObjects.Add(typeof(string));

            // Act
            string result = TemplateHelpers.TemplateHelper(html, metadata, "htmlFieldName", "templateName", DataBoundControlMode.ReadOnly, null /* additionalViewData */);

            // Assert
            Assert.AreEqual(String.Empty, result);
        }
Ejemplo n.º 6
0
        public static void ValidationMessage(
            HtmlHelper htmlHelper, XcstWriter output, string modelName, string?validationMessage = null, HtmlAttribs?htmlAttributes = null,
            string?tag = null)
        {
            if (modelName is null)
            {
                throw new ArgumentNullException(nameof(modelName));
            }

            ModelMetadata metadata = ModelMetadata.FromStringExpression(modelName, htmlHelper.ViewData);

            ValidationMessageHelper(htmlHelper, output, metadata, modelName, validationMessage, htmlAttributes, tag);
        }
 private static void SetViewdata(IDropDownAttribute attr, string name, ViewDataDictionary viewData)
 {
     if (!string.IsNullOrWhiteSpace(attr.DependsOn))
     {
         var metaData = ModelMetadata.FromStringExpression(attr.DependsOn, viewData);
         SetViewdataWithValue((DropDownAttribute)attr, name, viewData, metaData.Model);
     }
     else
     {
         var viewDataKey = "DDKey_" + name;
         viewData[viewDataKey] = viewData[viewDataKey] ?? attr.GetMethodResult();
     }
 }
Ejemplo n.º 8
0
        public static MvcHtmlString ValidationMessage(this HtmlHelper htmlHelper, string modelName, string validationMessage, IDictionary <string, object> htmlAttributes)
        {
            if (modelName == null)
            {
                throw new ArgumentNullException("modelName");
            }

            return(ValidationMessageHelper(htmlHelper,
                                           ModelMetadata.FromStringExpression(modelName, htmlHelper.ViewContext.ViewData),
                                           modelName,
                                           validationMessage,
                                           htmlAttributes));
        }
Ejemplo n.º 9
0
        // Validate

        public static void Validate(this HtmlHelper htmlHelper, string modelName)
        {
            if (modelName == null)
            {
                throw new ArgumentNullException("modelName");
            }

            ValidateHelper(
                htmlHelper,
                ModelMetadata.FromStringExpression(modelName, htmlHelper.ViewContext.ViewData),
                modelName
                );
        }
Ejemplo n.º 10
0
 /// <summary>
 /// Recupera os atributos de validação.
 /// </summary>
 /// <param name="instance"></param>
 /// <returns></returns>
 public static IDictionary <string, object> GetUnobtrusiveValidationAttributes(this IWidget instance)
 {
     if (instance.ViewContext.UnobtrusiveJavaScriptEnabled && instance.ViewData.ModelMetadata != null)
     {
         var name       = instance.Name;
         var htmlHelper = new HtmlHelper(instance.ViewContext, new WidgetViewDataContainer {
             ViewData = instance.ViewData
         });
         var metadata = instance.ModelMetadata ?? ModelMetadata.FromStringExpression(name, instance.ViewData);
         return(htmlHelper.GetUnobtrusiveValidationAttributes(name, metadata));
     }
     return(null);
 }
Ejemplo n.º 11
0
 private static IHtmlString RenderEditor(HtmlHelper html, string expression, string templateName = null, string htmlFieldName = null, object additionalViewData = null, Func <object, HelperResult> templateDelegate = null)
 {
     if (templateDelegate != null)
     {
         var metaData     = ModelMetadata.FromStringExpression(expression, html.ViewData);
         var helperResult = templateDelegate(metaData.Model);
         return(new MvcHtmlString(helperResult.ToHtmlString()));
     }
     else
     {
         return(html.Editor(expression, templateName, htmlFieldName, additionalViewData));
     }
 }
Ejemplo n.º 12
0
        public static void TextArea(
            HtmlHelper htmlHelper, XcstWriter output, string name, object?value, int rows, int columns, HtmlAttribs?htmlAttributes = null)
        {
            ModelMetadata metadata = ModelMetadata.FromStringExpression(name, htmlHelper.ViewData);

            if (value != null)
            {
                metadata.Model = value;
            }

            var rowsAndColumns = GetRowsAndColumnsDictionary(rows, columns);

            TextAreaHelper(htmlHelper, output, metadata, name, rowsAndColumns, htmlAttributes);
        }
Ejemplo n.º 13
0
        public void TemplateHelperConvertsNullModelsToNullDisplayTextInReadOnlyMode()
        {
            // Arrange
            HtmlHelper    html     = MakeHtmlHelper(new TemplateHelperModel());
            ModelMetadata metadata = ModelMetadata.FromStringExpression("MyProperty", html.ViewData);

            metadata.NullDisplayText = "NullDisplayText";

            // Act
            string result = TemplateHelpers.TemplateHelper(html, metadata, "htmlFieldName", "templateName", DataBoundControlMode.ReadOnly, null /* additionalViewData */, ExecuteTemplateSpy);

            // Assert
            Assert.AreEqual("Model = (null), ModelType = System.String, RealModelType = System.String, PropertyName = MyProperty, FormattedModelValue = NullDisplayText, HtmlFieldPrefix = FieldPrefix.htmlFieldName, TemplateName = templateName, Mode = ReadOnly", result);
        }
Ejemplo n.º 14
0
        public void ValidationMessageForWithClientValidation_Unobtrusive()
        {
            var originalProviders = ModelValidatorProviders.Providers.ToArray();

            ModelValidatorProviders.Providers.Clear();

            try
            {
                // Arrange
                HtmlHelper <ValidationModel> 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.ValidationMessageFor(m => m.baz);

                // 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);
                }
            }
        }
Ejemplo n.º 15
0
        public void TemplateHelperDoesNotApplyEditFormatStringInEditModeForNullModel()
        {
            // Arrange
            HtmlHelper    html     = MakeHtmlHelper(new TemplateHelperModel());
            ModelMetadata metadata = ModelMetadata.FromStringExpression("MyProperty", html.ViewData);

            metadata.EditFormatString = "{0} world!";

            // Act
            string result = TemplateHelpers.TemplateHelper(html, metadata, "htmlFieldName", "templateName", DataBoundControlMode.Edit, null /* additionalViewData */, ExecuteTemplateSpy);

            // Assert
            Assert.AreEqual("Model = (null), ModelType = System.String, RealModelType = System.String, PropertyName = MyProperty, FormattedModelValue = , HtmlFieldPrefix = FieldPrefix.htmlFieldName, TemplateName = templateName, Mode = Edit", result);
        }
Ejemplo n.º 16
0
        public void TemplateHelperAddsNullModelsTypeToVisitedObjects()      // DDB #224750
        {
            HtmlHelper         html     = MakeHtmlHelper(new TemplateHelperModel());
            ModelMetadata      metadata = ModelMetadata.FromStringExpression("MyProperty", html.ViewData);
            ViewDataDictionary viewData = null;

            // Act
            TemplateHelpers.TemplateHelper(html, metadata, "htmlFieldName", "templateName", DataBoundControlMode.ReadOnly, null /* additionalViewData */,
                                           (_html, _viewData, _templateName, _mode, _getViews) => { viewData = _viewData; return(String.Empty); });

            // Assert
            Assert.IsNotNull(viewData);
            Assert.IsTrue(viewData.TemplateInfo.VisitedObjects.Contains(typeof(string)));
        }
Ejemplo n.º 17
0
        public void TemplateHelperPreservesSameInstanceOfModelMetadata()      // DDB #225858
        {
            HtmlHelper         html             = MakeHtmlHelper(new TemplateHelperModel());
            ModelMetadata      metadata         = ModelMetadata.FromStringExpression("MyProperty", html.ViewData);
            ViewDataDictionary callbackViewData = null;

            // Act
            string result = TemplateHelpers.TemplateHelper(html, metadata, "htmlFieldName", "templateName", DataBoundControlMode.ReadOnly, null /* additionalViewData */,
                                                           (_html, _viewData, _templateName, _mode, _getViewNames) => { callbackViewData = _viewData; return(String.Empty); });

            // Assert
            Assert.IsNotNull(callbackViewData);
            Assert.AreSame(metadata, callbackViewData.ModelMetadata);
        }
Ejemplo n.º 18
0
        public void TemplateHelperNonNullNonEmptyStringModel()
        {
            // Arrange
            HtmlHelper html = MakeHtmlHelper(new TemplateHelperModel {
                MyProperty = "Hello"
            });
            ModelMetadata metadata = ModelMetadata.FromStringExpression("MyProperty", html.ViewData);

            // Act
            string result = TemplateHelpers.TemplateHelper(html, metadata, "htmlFieldName", "templateName", DataBoundControlMode.ReadOnly, null /* additionalViewData */, ExecuteTemplateSpy);

            // Assert
            Assert.AreEqual("Model = Hello, ModelType = System.String, RealModelType = System.String, PropertyName = MyProperty, FormattedModelValue = Hello, HtmlFieldPrefix = FieldPrefix.htmlFieldName, TemplateName = templateName, Mode = ReadOnly", result);
        }
Ejemplo n.º 19
0
        public void FromStringExpressionValueInModelProperty()
        {
            // Arrange
            DummyContactModel model = new DummyContactModel {
                FirstName = "John"
            };
            ViewDataDictionary viewData = new ViewDataDictionary(model);

            // Act
            ModelMetadata metadata = ModelMetadata.FromStringExpression("FirstName", viewData);

            // Assert
            Assert.Equal("John", metadata.Model);
        }
Ejemplo n.º 20
0
        public void ValidationMessageForWithClientValidation()
        {
            var originalProviders = ModelValidatorProviders.Providers.ToArray();

            ModelValidatorProviders.Providers.Clear();

            try {
                // Arrange
                HtmlHelper <ValidationModel> 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.Expect(v => v.GetClientValidationRules())
                .Returns(expectedValidationRules);
                Mock <ModelValidatorProvider> mockValidatorProvider = new Mock <ModelValidatorProvider>();
                mockValidatorProvider.Expect(vp => vp.GetValidators(It.IsAny <ModelMetadata>(), It.IsAny <ControllerContext>()))
                .Returns(new[] { mockValidator.Object });
                ModelValidatorProviders.Providers.Add(mockValidatorProvider.Object);

                // Act
                MvcHtmlString html = htmlHelper.ValidationMessageFor(m => m.baz);

                // Assert
                Assert.AreEqual(@"<span class=""field-validation-valid"" id=""baz_validationMessage""></span>", html.ToHtmlString(),
                                "ValidationMessageFor() should always return something if client validation is enabled.");
                Assert.IsNotNull(formContext.GetValidationMetadataForField("baz"));
                Assert.AreEqual("baz_validationMessage", formContext.FieldValidators["baz"].ValidationMessageId);
                CollectionAssert.AreEqual(expectedValidationRules, formContext.FieldValidators["baz"].ValidationRules.ToArray());
            }
            finally {
                ModelValidatorProviders.Providers.Clear();
                foreach (var provider in originalProviders)
                {
                    ModelValidatorProviders.Providers.Add(provider);
                }
            }
        }
Ejemplo n.º 21
0
        public override MvcHtmlString Render()
        {
            var tagBuilder = new TagBuilder("label");

            tagBuilder.Attributes.Add("for", TagBuilder.CreateSanitizedId(this.htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(this.property)));

            var    metadata  = ModelMetadata.FromStringExpression(this.property, this.htmlHelper.ViewData);
            string innerText = Name ?? metadata.DisplayName ?? this.property;

            tagBuilder.SetInnerText(innerText);

            tagBuilder.MergeAttributes(this.attributes, true);
            return(new MvcHtmlString(tagBuilder.ToString(TagRenderMode.Normal)));
        }
Ejemplo n.º 22
0
        public void TextAreaHelperDoesNotEncodeInnerHtmlPrefix()
        {
            // Arrange
            HtmlHelper    helper   = MvcHelper.GetHtmlHelper();
            ModelMetadata metadata = ModelMetadata.FromStringExpression("foo", helper.ViewData);

            metadata.Model = "<model>";

            // Act
            MvcHtmlString html = TextAreaExtensions.TextAreaHelper(helper, metadata, "testEncoding", rowsAndColumns: null,
                                                                   htmlAttributes: null, innerHtmlPrefix: "<prefix>");

            // Assert
            Assert.Equal(@"<textarea id=""testEncoding"" name=""testEncoding""><prefix>&lt;model&gt;</textarea>", html.ToHtmlString());
        }
Ejemplo n.º 23
0
        public void FromStringExpressionEmptyExpressionReturnsExistingModelMetadata()
        {
            // Arrange
            Mock <ModelMetadataProvider> provider = new Mock <ModelMetadataProvider>();
            ModelMetadata      metadata           = new ModelMetadata(provider.Object, null, null, typeof(object), null);
            ViewDataDictionary viewData           = new ViewDataDictionary();

            viewData.ModelMetadata = metadata;

            // Act
            ModelMetadata result = ModelMetadata.FromStringExpression(String.Empty, viewData, provider.Object);

            // Assert
            Assert.Same(metadata, result);
        }
Ejemplo n.º 24
0
 public BootstrapInputList <TModel, TSource, SValue, SText> RadioButtonList <TSource, SValue, SText>(
     string htmlFieldName,
     Expression <Func <TModel, IEnumerable <TSource> > > sourceDataExpression,
     Expression <Func <TSource, SValue> > valueExpression,
     Expression <Func <TSource, SText> > textExpression)
 {
     return(new BootstrapInputList <TModel, TSource, SValue, SText>(
                Html,
                htmlFieldName,
                ModelMetadata.FromStringExpression(htmlFieldName, Html.ViewData),
                sourceDataExpression,
                valueExpression,
                textExpression,
                BootstrapInputType.RadioList));
 }
Ejemplo n.º 25
0
        public static MvcHtmlString LabelEx(this HtmlHelper htmlHelper, string expression, IDictionary <string, object> htmlAttributes, Action <ModelMetadata> metadataModifer)
        {
            IEnumerable <ILabelViewModifier> modifier;
            var metadata = ModelMetadata.FromStringExpression(expression, htmlHelper.ViewData);

            if (metadata != null && metadata.TryGetExtent <IEnumerable <ILabelViewModifier> >(out modifier))
            {
                modifier.MapLabelToHtmlAttributes(ref expression, ref htmlAttributes);
            }
            if (metadataModifer != null)
            {
                metadataModifer(metadata);
            }
            return(LabelHelperEx(htmlHelper, metadata, expression, htmlAttributes));
        }
 public BootstrapControlGroupInputList <TModel, TSource, SValue, SText> CheckBoxList <TSource, SValue, SText>(
     string htmlFieldName,
     Expression <Func <TModel, IEnumerable <TSource> > > sourceDataExpression,
     Expression <Func <TSource, SValue> > valueExpression,
     Expression <Func <TSource, SText> > textExpression)
 {
     return(new BootstrapControlGroupInputList <TModel, TSource, SValue, SText>(
                html,
                htmlFieldName,
                ModelMetadata.FromStringExpression(htmlFieldName, html.ViewData),
                sourceDataExpression,
                valueExpression,
                textExpression,
                BootstrapInputType.CheckBoxList));
 }
Ejemplo n.º 27
0
        /// <summary>
        ///     Zeigt statischen Inhalt (der Wert im Model) mit Label an.
        ///     Der angezeigte Wert wird nicht gebunden!
        /// </summary>
        /// <param name="expression"></param>
        /// <param name="placeholder">Der Wert der angezeigt wird, wenn der Wert null ist.</param>
        /// <param name="label"></param>
        /// <param name="formatString">Optionale Angabe zur Formatierung des Inhaltes.</param>
        /// <returns></returns>
        public MvcHtmlString Static <TProperty>(Expression <Func <TModel, TProperty> > expression, string label = null,
                                                string placeholder = null, string formatString = null)
        {
            ModelMetadata modelMetadata = ModelMetadata.FromLambdaExpression(expression, Helper.ViewData);

            if (modelMetadata.PropertyName != "DisplayName")
            {
                label = FormControlModel.GetLabel(modelMetadata, label);
            }
            else
            {
                string        reducedExpression   = expression.ToString().Replace(".DisplayName", "").Split(new[] { '.' }, 2, StringSplitOptions.RemoveEmptyEntries)[1];
                ModelMetadata parentModelMetadata = ModelMetadata.FromStringExpression(reducedExpression, Helper.ViewData);
                label = FormControlModel.GetLabel(parentModelMetadata, label);
            }


            object value;

            if (modelMetadata.Model != null)
            {
                /*Wenn die Expression auf einen Wert ungleich NULL zeigt, zeige diesen als ToString an*/
                value = modelMetadata.Model;

                if (modelMetadata.ModelType.IsEnum)
                {
                    string localizedEnumValue = LabelHelper.GetLabelFromResourceByPropertyName <Resources_Domain>(modelMetadata.ModelType, value.ToString());
                    if (!string.IsNullOrWhiteSpace(localizedEnumValue))
                    {
                        value = localizedEnumValue;
                    }
                }
                if (!string.IsNullOrWhiteSpace(formatString))
                {
                    /*Es ist ein Format für die Ausgabe angegeben => Formatieren!*/
                    value = string.Format(formatString, value);
                }
            }
            else
            {
                /*Wenn die Expression auf einen Wert zeigt der NULL ist, wird der Platzhalter-Text verwendet.*/
                value = placeholder;
            }

            StaticControlModel model = new StaticControlModel(Helper, label, value);

            return(Helper.Partial("EditorTemplates/Forms/Static", model));
        }
Ejemplo n.º 28
0
        private TBuilder InitFieldForBuilder <TField, TBuilder>(string expression, bool setId, Func <object, object> convert = null, string format = null)
            where TField : Field
            where TBuilder : Field.Builder <TField, TBuilder>, new()
        {
            TBuilder builder = new TBuilder();
            var      cmp     = builder.ToComponent();

            cmp.ViewContext            = this.HtmlHelper.ViewContext;
            cmp.IDFromControlFor       = setId;
            cmp.ConvertControlForValue = convert;
            cmp.FormatControlForValue  = format;

            builder.ControlFor(expression);
            cmp.SetControlFor(ModelMetadata.FromStringExpression(expression, this.HtmlHelper.ViewData));
            return(builder);
        }
Ejemplo n.º 29
0
 internal static MvcHtmlString Label(
     this HtmlHelper html,
     string expression,
     string labelText,
     IDictionary <string, object> htmlAttributes,
     ModelMetadataProvider metadataProvider
     )
 {
     return(LabelHelper(
                html,
                ModelMetadata.FromStringExpression(expression, html.ViewData, metadataProvider),
                expression,
                labelText,
                htmlAttributes
                ));
 }
Ejemplo n.º 30
0
        public void FromStringExpressionWithNullModelButValidModelMetadataShouldReturnProperPropertyMetadata()
        {
            // Arrange
            ViewDataDictionary viewData = new ViewDataDictionary();

            viewData.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(DummyContactModel));

            // Act
            ModelMetadata result = ModelMetadata.FromStringExpression("NullableIntValue", viewData);

            // Assert
            Assert.Null(result.Model);
            Assert.Equal(typeof(Nullable <int>), result.ModelType);
            Assert.Equal("NullableIntValue", result.PropertyName);
            Assert.Equal(typeof(DummyContactModel), result.ContainerType);
        }