我的视图模型中的一些decimal
和decimal?
属性被标记为“百分比”数据类型,以及其他数据注释,例如:
[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);
}
}