MVC2의 POST 데이터에서 바인딩되기 전에 일부 값을 필터링해야합니다. 불행히도 때로는 "N/A"십진수로 매핑 할 수있는 폼 값을 전달하는 클라이언트 쪽 코드를 변경할 수 없습니다? 유형. "N/A"가 바인딩되거나 유효성 검사되기 전에 POST 값을 비워두면됩니다.MVC ModelBinders를 사용하여 바인딩 전에 필터 값 필터링
나는 그것이 DefaultModelBinder를 확장 ModelBinder를을 사용하여 작업을 진행하기 위해 모든 아침 시도했다 :
난 데 문제는 내가 원래 게시 된 값에 접근하는 방법을 몰라public class DecimalFilterBinder : DefaultModelBinder
{
protected override void BindProperty(ControllerContext controllerContext,
ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
{
if (propertyDescriptor.PropertyType == typeof(decimal?))
{
var model = bindingContext.Model;
PropertyInfo property = model.GetType().GetProperty(propertyDescriptor.Name);
var httpRequest = controllerContext.RequestContext.HttpContext.Request;
if (httpRequest.Form[propertyDescriptor.Name] == "-" ||
httpRequest.Form[propertyDescriptor.Name] == "N/A")
{
property.SetValue(model, null, null);
}
else
{
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
}
else
{
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
}
}
그것이 목록 내에있을 때. Form[propertyDescriptor.Name]
은 양식의 목록 항목에 포함되어 있으므로 입력 할 수 없습니다 (예 : 입력이 실제로는 Values[0].Property1
). 모델 바인더를 global.asax에 연결하여 잘 실행하면 기본 바인딩이 발생하기 전에 빈 문자열로 필터링하기 위해 원래 폼 값을 유지하는 방법을 모르겠습니다.