Tôi có một loạt các biểu mẫu nơi nhập các giá trị tiền tệ và tôi muốn chúng có thể nhập "$ 1,234.56". Theo mặc định, trình kết nối mô hình sẽ không phân tích cú pháp đó thành số thập phân.Làm cách nào để lọc dữ liệu biểu mẫu bằng mô hình liên kết tùy chỉnh
Điều tôi đang nghĩ là tạo mô hình tùy chỉnh kết nối phần thừa kế DefaultModelBinder, ghi đè phương thức BindProperty, kiểm tra xem kiểu mô tả thuộc tính có phải là số thập phân hay không, chỉ cần bỏ ra $ và, từ các giá trị.
Đây có phải là cách tiếp cận tốt nhất không?
Code:
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);
}
}
Cập nhật
Đây là những gì tôi đã kết thúc thực hiện:
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);
}
}
hãy nhìn vào bài đăng này từ Haacked: http://haacked.com/archive/2011/03/ 19/fixing-binding-to-decimals.aspx – VinnyG