public void OnMetadataCreated(System.Web.Mvc.ModelMetadata metadata)
        {
            switch (RenderMode)
            {
            case RenderMode.DisplayModeOnly:
                metadata.ShowForDisplay = true;
                metadata.ShowForEdit    = false;
                break;

            case RenderMode.EditModeOnly:
                metadata.ShowForDisplay = false;
                metadata.ShowForEdit    = true;
                break;

            case RenderMode.None:
                metadata.ShowForDisplay = false;
                metadata.ShowForEdit    = false;
                break;

            case RenderMode.Any:
                metadata.ShowForDisplay = true;
                metadata.ShowForEdit    = true;
                break;
            }
        }
Exemple #2
0
        public static MvcHtmlString AngularRadioButtonFor <TModel, TProperty>(
            this HtmlHelper <TModel> helper,
            Expression <Func <TModel, TProperty> > expression,
            string ngModel        = null,
            string value          = null,
            object htmlAttributes = null)
        {
            //helper.ViewData["htmlAttributes"]
            var htmlAttributesData = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);

            //htmlAttributes

            System.Web.Mvc.ModelMetadata oModelMetadata =
                System.Web.Mvc.ModelMetadata.FromLambdaExpression(expression, helper.ViewData);


            if (ngModel != null)
            {
                if (htmlAttributesData.ContainsKey("ng-model") == false)
                {
                    htmlAttributesData.Add("ng-model", ngModel);
                }
            }

            //htmlAttributes = MyHtmlHelpers.ToAnonymousObject(htmlAttributesData);

            return(helper.RadioButtonFor(expression, value, htmlAttributesData));
        }
 public void TransformMetadata(System.Web.Mvc.ModelMetadata metadata, IEnumerable <Attribute> attributes)
 {
     if (!string.IsNullOrEmpty(metadata.PropertyName) &&
         string.IsNullOrEmpty(metadata.DisplayName))
     {
         metadata.DisplayName = GetStringWithSpaces(metadata.PropertyName);
     }
 }
        internal static MvcHtmlString DisplayNameHelper(ModelMetadata metadata, string htmlFieldName)
        {
            // We don't call ModelMetadata.GetDisplayName here because we want to fall back to the field name rather than the ModelType.
            // This is similar to how the LabelHelpers get the text of a label.
            string resolvedDisplayName = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();

            return(new MvcHtmlString(HttpUtility.HtmlEncode(resolvedDisplayName)));
        }
Exemple #5
0
        public IEnumerable <ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            ErrorMessage = UmbracoValidationHelper.GetPropertyValue(_propertyAlias);

            var error = FormatErrorMessage(metadata.DisplayName);
            var rule  = new ModelClientValidationEqualToRule(error, _otherProperty);

            yield return(rule);
        }
 public CustRangeAttributeAdapter(System.Web.Mvc.ModelMetadata metadata, ControllerContext context, System.ComponentModel.DataAnnotations.RangeAttribute attribute)
     : base(metadata, context, attribute)
 {
     if (Convert.ToInt32(attribute.Minimum) == 0)
     {
         attribute.ErrorMessageResourceType = typeof(Messages);
         attribute.ErrorMessageResourceName = "Error_PositiveNumbersOnly";
     }
 }
Exemple #7
0
 public IEnumerable <ModelClientValidationRule> GetClientValidationRules(System.Web.Mvc.ModelMetadata metadata, ControllerContext context)
 {
     // Kodus to "Chad" http://stackoverflow.com/a/9914117
     yield return(new ModelClientValidationRule
     {
         ErrorMessage = this.ErrorMessage,
         ValidationType = "email"
     });
 }
        //new method
        public IEnumerable <ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule();

            rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
            rule.ValidationParameters.Add("chars", _chars);
            rule.ValidationType = "customvalidationclass";
            yield return(rule);
        }
Exemple #9
0
        /// <summary>
        /// Custom validation for BsSelectList&lt;T&gt;
        /// </summary>
        public override IEnumerable <ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context)
        {
            var res = new List <ModelValidator>();

            if (metadata == null || metadata.ContainerType == null)
            {
                return(res);
            }

            if (metadata.ModelType.InheritsOrImplements(typeof(BsSelectList <>)))
            {
                var selectedValuesMetadata = metadata.Properties.Where(r => r.PropertyName == "SelectedValues").FirstOrDefault();
                var propertyInfo           = metadata.ContainerType.GetProperties().Where(r => r.Name == metadata.PropertyName).FirstOrDefault();

                if (propertyInfo == null)
                {
                    return(res);
                }

                //get validation attributes for parent
                var attributes =
                    propertyInfo.GetCustomAttributes(true)
                    .Where(r => r is ValidationAttribute)
                    .ToList();

                //copy validation meta to parent from SelectedValues
                foreach (var attribute in attributes)
                {
                    res.Add(new DataAnnotationsModelValidator(selectedValuesMetadata, context, attribute as ValidationAttribute));
                }
            }

            if (metadata.ModelType.InheritsOrImplements(typeof(BsRange <>)) || metadata.ModelType == typeof(BsDateTime))
            {
                var selectedValuesMetadata = metadata.Properties.Where(r => r.PropertyName == "TextValue").FirstOrDefault();
                var propertyInfo           = metadata.ContainerType.GetProperties().Where(r => r.Name == metadata.PropertyName).FirstOrDefault();

                if (propertyInfo == null)
                {
                    return(res);
                }

                //get validation attributes for parent
                var attributes =
                    propertyInfo.GetCustomAttributes(true)
                    .Where(r => r is ValidationAttribute)
                    .ToList();

                //copy validation meta to parent from TextValue
                foreach (var attribute in attributes)
                {
                    res.Add(new DataAnnotationsModelValidator(selectedValuesMetadata, context, attribute as ValidationAttribute));
                }
            }
            return(res);
        }
 public MyRequiredAttributeAdapter(
     System.Web.Mvc.ModelMetadata metadata,
     ControllerContext context,
     RequiredAttribute attribute
 )
     : base(metadata, context, attribute)
 {
     //attribute.ErrorMessageResourceType = typeof(MyNewResource);
     //attribute.ErrorMessageResourceName = "PropertyValueRequired";
 }
 public IEnumerable <System.Web.Mvc.ModelClientValidationRule> GetClientValidationRules(
     System.Web.Mvc.ModelMetadata metadata,
     System.Web.Mvc.ControllerContext context)
 {
     yield return(new System.Web.Mvc.ModelClientValidationRule
     {
         ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
         ValidationType = "booleanrequired"
     });
 }
        public IEnumerable <ModelClientValidationRule> GetClientValidationRules(System.Web.Mvc.ModelMetadata metadata, ControllerContext context)
        {
            this.TrySetErrorMessage(_errorMessageDictionaryKey);

            // Kodus to "Chad" http://stackoverflow.com/a/9914117
            yield return(new ModelClientValidationRule
            {
                ErrorMessage = FormatErrorMessage(metadata.DisplayName),
                ValidationType = this.DataType.ToString().ToLower()
            });
        }
Exemple #13
0
 public IEnumerable <ModelClientValidationRule> GetClientValidationRules(
     System.Web.Mvc.ModelMetadata metadata, System.Web.Mvc.ControllerContext context)
 {
     return(new[]
     {
         new ModelClientValidationRule
         {
             ValidationType = "checkboxrequired", ErrorMessage = ValidationResource.checkboxrequired
         }
     });
 }
        public static IHtmlString DisplyPluralNameFor <TModel, TValue>(this HtmlHelper <TModel> html, Expression <Func <TModel, TValue> > expression)
        {
            var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);

            if (metadata.AdditionalValues.ContainsKey("DisplyNamePlural"))
            {
                return(new HtmlString((string)metadata.AdditionalValues["DisplyNamePlural"]));
            }

            return(new HtmlString(""));
        }
        public static IHtmlString TooltipFor <TModel, TValue>(this HtmlHelper <TModel> html, Expression <Func <TModel, TValue> > expression)
        {
            var metadata = ModelMetadata.FromLambdaExpression <TModel, TValue>(expression, html.ViewData);

            if (metadata.AdditionalValues.ContainsKey("Tooltip"))
            {
                return(new HtmlString((string)metadata.AdditionalValues["Tooltip"]));
            }

            return(new HtmlString(""));
        }
 public CustomStringLengthAttribute(
     System.Web.Mvc.ModelMetadata metadata,
     ControllerContext context,
     StringLengthAttribute attribute)
     : base(metadata, context, attribute)
 {
     if (string.IsNullOrEmpty(attribute.ErrorMessage))
     {
         attribute.ErrorMessageResourceType = typeof(DefaultResource);
         attribute.ErrorMessageResourceName = "StringLength";
     }
 }
 /// <summary>
 ///   When implemented in a class, returns client validation rules for that class.
 /// </summary>
 /// <returns> The client validation rules for this validator. </returns>
 /// <param name="metadata"> The model metadata. </param>
 /// <param name="context"> The controller context. </param>
 public IEnumerable <ModelClientValidationRule> GetClientValidationRules(System.Web.Mvc.ModelMetadata metadata,
                                                                         ControllerContext context)
 {
     yield return(new ModelClientValidationRule
     {
         ErrorMessage =
             String.IsNullOrEmpty(ErrorMessage)
                                  ? FormatErrorMessage(metadata.DisplayName)
                                  : ErrorMessage,
         ValidationType = "enforcetrue"
     });
 }
        public static IHtmlString DisplyModelPluralName <TModel, TValue>(this HtmlHelper <IEnumerable <TModel> > html, Expression <Func <TModel, TValue> > expression)
        {
            HtmlString singleModelItem = DisplayNameForSingleModelItem(html, expression);
            HtmlString ModelPluralName = null;

            var metadata = ModelMetadata.FromLambdaExpression(expression, new ViewDataDictionary <TModel>());

            if (metadata.AdditionalValues.ContainsKey("DisplyNamePlural"))
            {
                ModelPluralName = new HtmlString((string)metadata.AdditionalValues["DisplyNamePlural"]);
            }

            return(ModelPluralName ?? singleModelItem ?? new HtmlString(""));
        }
 /// <summary>
 /// Returns the html for the date picker input, including validation attributes and message.
 /// </summary>
 /// <param name="helper">
 /// The html helper.
 /// </param>
 /// <param name="metadata">
 /// The meta data of the property to display the date for.
 /// </param>
 /// <param name="name">
 /// The fully qualified name of the property.
 /// </param>
 /// <returns></returns>
 private static string DatePickerInput(System.Web.Mvc.HtmlHelper helper, System.Web.Mvc.ModelMetadata metadata, string name)
 {
     // Construct the input
     System.Web.Mvc.TagBuilder input = new System.Web.Mvc.TagBuilder("input");
     input.AddCssClass("datepicker-input");
     input.MergeAttribute("type", "text");
     input.MergeAttribute("id", System.Web.Mvc.HtmlHelper.GenerateIdFromName(name));
     input.MergeAttribute("autocomplete", "off");
     input.MergeAttribute("name", name);
     input.MergeAttributes(helper.GetUnobtrusiveValidationAttributes(name, metadata));
     if (metadata.Model != null)
     {
         input.MergeAttribute("value", ((DateTime)metadata.Model).ToShortDateString());
     }
     // Return the html
     return(input.ToString());
 }
Exemple #20
0
        public static MvcHtmlString AngularCheckboxFor <TModel>(
            this HtmlHelper <TModel> helper,
            Expression <Func <TModel, bool> > expression,
            string ngModel        = null,
            object htmlAttributes = null,
            string ngTrueValue    = null,
            string ngFalseValue   = null)
        {
            //helper.ViewData["htmlAttributes"]
            var htmlAttributesData = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);

            //htmlAttributes

            System.Web.Mvc.ModelMetadata oModelMetadata =
                System.Web.Mvc.ModelMetadata.FromLambdaExpression(expression, helper.ViewData);


            if (ngModel != null)
            {
                if (htmlAttributesData.ContainsKey("ng-model") == false)
                {
                    htmlAttributesData.Add("ng-model", ngModel);
                }
            }

            if (ngTrueValue != null)
            {
                if (htmlAttributesData.ContainsKey("ng-true-value") == false)
                {
                    htmlAttributesData.Add("ng-true-value", ngTrueValue);
                }
            }

            if (ngFalseValue != null)
            {
                if (htmlAttributesData.ContainsKey("ng-false-value") == false)
                {
                    htmlAttributesData.Add("ng-false-value", ngFalseValue);
                }
            }

            //htmlAttributes = MyHtmlHelpers.ToAnonymousObject(htmlAttributesData);

            return(helper.CheckBoxFor(expression, htmlAttributesData));
        }
Exemple #21
0
        protected override System.Web.Mvc.ModelMetadata CreateMetadata(
            IEnumerable <Attribute> attributes,
            Type containerType,
            Func <object> modelAccessor,
            Type modelType,
            string propertyName)
        {
            Attribute[] attributesArray           = attributes as Attribute[] ?? attributes.ToArray();
            System.Web.Mvc.ModelMetadata metadata = base.CreateMetadata(
                attributesArray,
                containerType,
                modelAccessor,
                modelType,
                propertyName);

            metadataFilters.ForEach(m => m.TransformMetadata(metadata, attributesArray));

            return(metadata);
        }
        /// <summary>
        ///   When implemented in a class, returns client validation rules for that class.
        /// </summary>
        /// <returns> The client validation rules for this validator. </returns>
        /// <param name="metadata"> The model metadata. </param>
        /// <param name="context"> The controller context. </param>
        public IEnumerable <ModelClientValidationRule> GetClientValidationRules(System.Web.Mvc.ModelMetadata metadata,
                                                                                ControllerContext context)
        {
            var errormessage = String.IsNullOrEmpty(this.ErrorMessage)
                                   ? this.FormatErrorMessage(metadata.DisplayName)
                                   : string.Format(this.ErrorMessage, new object[]
            {
                metadata.DisplayName,
                this.MaximumLength,
                this.MinimumLength
            });
            var rule = new ModelClientValidationRule
            {
                ErrorMessage   = errormessage,
                ValidationType = "cnlength"
            };

            rule.ValidationParameters["min"] = this.MinimumLength;
            rule.ValidationParameters["max"] = this.MaximumLength;

            yield return(rule);
        }
Exemple #23
0
        public IEnumerable <ModelClientValidationRule> GetClientValidationRules(System.Web.Mvc.ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule()
            {
                ErrorMessage   = string.IsNullOrEmpty(ErrorMessage) ? FormatErrorMessage(metadata.DisplayName) : ErrorMessage,
                ValidationType = "agerange",
            };
            var dates = new List <string>
            {
                MinAge.ToString(),
                MaxAge.ToString()
            };
            var errorMessages = new List <string>
            {
                MinAgeErrorMessage,
                MaxAgeErrorMessage,
                InvalidErrorMessage
            };

            rule.ValidationParameters.Add("dates", string.Join(" ", dates));
            rule.ValidationParameters.Add("errormessages", string.Join(",", errorMessages));
            yield return(rule);
        }
        /// <summary>
        /// 下拉枚举
        /// </summary>
        /// <typeparam name="TModel">Model</typeparam>
        /// <typeparam name="TProperty">属性</typeparam>
        /// <param name="htmlHelper"></param>
        /// <param name="expression"></param>
        /// <param name="htmlAttributes"></param>
        /// <returns></returns>
        public static MvcHtmlString EnumToolsSelectFor <TModel, TProperty>(this HtmlHelper <TModel> htmlHelper, Expression <Func <TModel, TProperty> > expression, object htmlAttributes = null)
        {
            // 获取元数据meta
            System.Web.Mvc.ModelMetadata modelMetadata = System.Web.Mvc.ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

            Type enumType = modelMetadata.ModelType;

            // 设置id name的属性值
            var rvd = new RouteValueDictionary
            {
                { "id", modelMetadata.PropertyName },
                { "name", modelMetadata.PropertyName }
            };

            // 添加自定义属性
            if (htmlAttributes != null)
            {
                RouteValueDictionary htmlAttr = htmlAttributes as RouteValueDictionary ?? HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
                foreach (var item in htmlAttr)
                {
                    rvd.Add(item.Key, item.Value);
                }
            }

            // 获取验证信息
            IDictionary <string, object> validationAttributes = htmlHelper.GetUnobtrusiveValidationAttributes(modelMetadata.PropertyName, modelMetadata);

            // 添加至自定义属性
            if (validationAttributes != null)
            {
                foreach (var item in validationAttributes)
                {
                    rvd.Add(item.Key, item.Value);
                }
            }
            return(htmlHelper.EnumToolsSelect(enumType, Convert.ToInt32(modelMetadata.Model), rvd));
        }
        protected override IEnumerable <ModelValidator> GetValidators(System.Web.Mvc.ModelMetadata metadata,
                                                                      ControllerContext context, IEnumerable <Attribute> attributes)
        {
            if (attributes == null)
            {
                return(base.GetValidators(metadata, context, null));
            }
            if (string.IsNullOrEmpty(metadata.PropertyName))
            {
                return(base.GetValidators(metadata, context, attributes));
            }
            //DisallowHtml should not be added if a property allows html input
            var isHtmlInput = attributes.OfType <AllowHtmlAttribute>().Any();

            if (isHtmlInput)
            {
                return(base.GetValidators(metadata, context, attributes));
            }
            attributes = new List <Attribute>(attributes)
            {
                new DisallowHtmlAttribute()
            };
            return(base.GetValidators(metadata, context, attributes));
        }
 internal static MvcHtmlString DisplayNameForInternal <TModel, TValue>(this HtmlHelper <TModel> html, Expression <Func <TModel, TValue> > expression, ModelMetadataProvider metadataProvider)
 {
     return(DisplayNameHelper(ModelMetadata.FromLambdaExpression(expression, html.ViewData),
                              ExpressionHelper.GetExpressionText(expression)));
 }
 //[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", Justification = "This is an extension method")]
 internal static MvcHtmlString DisplayNameForInternal <TModel, TValue>(this HtmlHelper <IEnumerable <TModel> > html, Expression <Func <TModel, TValue> > expression, ModelMetadataProvider metadataProvider)
 {
     return(DisplayNameHelper(ModelMetadata.FromLambdaExpression(expression, new ViewDataDictionary <TModel>()),
                              ExpressionHelper.GetExpressionText(expression)));
 }
 internal static MvcHtmlString DisplayNameInternal(this HtmlHelper html, string expression, ModelMetadataProvider metadataProvider)
 {
     return(DisplayNameHelper(ModelMetadata.FromStringExpression(expression, html.ViewData),
                              expression));
 }
Exemple #29
0
 public LOSTreeListColumnCollection(MVCxTreeListColumnCollection columns, System.Web.Mvc.ModelMetadata modelMetadata, ViewContext viewContext) : this(columns)
 {
     this.modelMetadata = modelMetadata;
     this.viewContext   = viewContext;
 }
Exemple #30
0
 public void OnMetadataCreated(System.Web.Mvc.ModelMetadata metadata)
 {
     metadata.AdditionalValues.Add(HttpPostedFileBasePropertyKey, HttpPostedFileBaseProperty);
 }