Пример #1
0
        /// <summary> 设置指定名称实体字段数据  </summary>
        bool RefreshModelProperty <R>(ValidationProperty <R> value, [CallerMemberName] string propertyName = "")
        {
            var p = typeof(T).GetProperty(propertyName);

            if (!p.CanWrite)
            {
                value.Message = "只读字段不可以修改";
                return(false);
            }

            value.Message = null;

            //  Do :判断数据验证
            var collection = p.GetCustomAttributes <ValidationAttribute>()?.ToList();

            if (collection != null)
            {
                foreach (var r in collection)
                {
                    if (!r.IsValid(value.Value))
                    {
                        string display = p.GetCustomAttributes <DisplayAttribute>()?.FirstOrDefault()?.Name;

                        value.Message = r.ErrorMessage ?? r.FormatErrorMessage(display ?? p.Name);

                        //  Do :保存实体验证失败
                        return(false);
                    }
                }
            }

            p.SetValue(this.Model, value.Value);

            return(true);
        }
Пример #2
0
        /// <summary> 获取指定名称实体字段数据 </summary>
        protected ValidationProperty <R> CreateModelProperty <R>([CallerMemberName] string propertyName = "")
        {
            ValidationProperty <R> value = new ValidationProperty <R>();

            //  Do :值改变时检查数据,并更新实体字段
            value.ValueChanged = l =>
            {
                this.RefreshModelProperty(value, propertyName);
            };

            var p = typeof(T).GetProperty(propertyName);

            string display = p.GetCustomAttributes <DisplayAttribute>()?.FirstOrDefault()?.Name;

            value.Name = p.Name;

            value.DisplayName = display ?? value.Name;

            if (!p.CanRead)
            {
                value.Message = "只写字段不支持读取数据";
                return(value);
            }

            //  Do :判断数据验证
            var collection = p.GetCustomAttributes <ValidationAttribute>()?.ToList();

            if (collection != null)
            {
                foreach (var r in collection)
                {
                    if (!r.IsValid(value.Value))
                    {
                        value.Message = r.ErrorMessage ?? r.FormatErrorMessage(display ?? p.Name);

                        //  Do :保存实体验证失败
                        break;
                    }
                }
            }

            value.Flag = p.GetCustomAttributes <RequiredAttribute>()?.FirstOrDefault() != null ? "*" : "";

            value.Value = (R)p.GetValue(this.Model);

            return(value);
        }