加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 在将模型值传递给DefaultModelBinder.BindModel

发布时间:2020-12-16 06:59:08 所属栏目:asp.Net 来源:网络整理
导读:一些小数和小数?我的视图模型中的属性标记为“百分比”数据类型以及其他数据注释,例如: [DataType("Percent")][Display(Name = "Percent of foo completed")][Range(0,1)]public decimal? FooPercent { get; set; } 我想允许用户在输入数据时有一些灵活性,
一些小数和小数?我的视图模型中的属性标记为“百分比”数据类型以及其他数据注释,例如:

[DataType("Percent")]
[Display(Name = "Percent of foo completed")]
[Range(0,1)]
public decimal? FooPercent { get; set; }

我想允许用户在输入数据时有一些灵活性,即有或没有百分号,中间空格等.但我仍然想使用DefaultModelBinder行为来获取其所有功能,例如检查RangeAttribute并添加适当的验证消息.

有没有办法解析和更改模型值,然后传递它?这是我正在尝试的,但我得到一个运行时异常. (忽略实际的解析逻辑;这不是它的最终形式.此时我只对模型替换问题感兴趣.)

public class PercentModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext,ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelMetadata.DataTypeName == "Percent")
        {
            ValueProviderResult result =
                bindingContext.ValueProvider.GetValue(
                    bindingContext.ModelName);
            if (result != null)
            {
                string stringValue =
                    (string)result.ConvertTo(typeof(string));
                decimal decimalValue;
                if (!string.IsNullOrWhiteSpace(stringValue) &&
                    decimal.TryParse(
                        stringValue.TrimEnd(new char[] { '%',' ' }),out decimalValue))
                {
                    decimalValue /= 100.0m;

                    // EXCEPTION : This property setter is obsolete,// because its value is derived from 
                    // ModelMetadata.Model now.
                    bindingContext.Model = decimalValue;
                }
            }
        }

        return base.BindModel(controllerContext,bindingContext);
    }
}

解决方法

没关系,这是对MVC循环中验证发生位置的基本误解.在MVC源代码中花了一些时间后,我看到它是如何工作的.

如果它对其他人有帮助,这里有什么对我有用:

[DataType("Percent")]
[Display(Name = "Percent of foo completed")]
[Range(0.0d,1.0d,ErrorMessage="The field {0} must be between {1:P0} and {2:P0}.")]
public decimal? FooPercent { get; set; }

在绑定器中,您只需返回值:

public class PercentModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext,out decimalValue))
                {
                    return decimalValue / 100.0m;
                }
            }
        }

        return base.BindModel(controllerContext,bindingContext);
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读