我有一堆表單,其中輸入貨幣值,我希望它們能夠輸入「$ 1,234.56」。默認情況下,模型聯編程序不會將其解析爲小數。如何使用自定義模型過濾器過濾表單數據
我在做的是創建一個自定義模型綁定器繼承DefaultModelBinder,重寫BindProperty方法,檢查屬性描述符類型是否是十進制的,如果是,只需從值中刪除$和。
這是最好的方法嗎?
代碼:
public class CustomModelBinder : DefaultModelBinder
{
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
{
if(propertyDescriptor.PropertyType == typeof(decimal) || propertyDescriptor.PropertyType == typeof(decimal?))
{
var newValue = Regex.Replace(bindingContext.ValueProvider[propertyDescriptor.Name].AttemptedValue, @"[$,]", "", RegexOptions.Compiled);
bindingContext.ValueProvider[propertyDescriptor.Name] = new ValueProviderResult(newValue, newValue, bindingContext.ValueProvider[propertyDescriptor.Name].Culture);
}
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
}
更新
這是我落得這樣做:
public class CustomModelBinder : DataAnnotationsModelBinder
{
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
{
if(propertyDescriptor.PropertyType == typeof(decimal) || propertyDescriptor.PropertyType == typeof(decimal?))
{
decimal newValue;
decimal.TryParse(bindingContext.ValueProvider[propertyDescriptor.Name].AttemptedValue, NumberStyles.Currency, null, out newValue);
bindingContext.ValueProvider[propertyDescriptor.Name] = new ValueProviderResult(newValue, newValue.ToString(), bindingContext.ValueProvider[propertyDescriptor.Name].Culture);
}
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
}
看一看這個職位從Haacked:http://haacked.com/archive/2011/03/ 19/fix-binding-to-decimals.aspx – VinnyG 2011-04-22 15:51:08