在绑定到MVC2中的POST数据之前,我需要过滤掉一些值。不幸的是,我不能改变客户端代码,它有时会传递"N/A“给要映射为十进制的表单值?类型。需要发生的是,如果"N/A“是POST值,则在绑定/验证之前将其清除。
我整个上午都在尝试使用一个扩展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中,并且运行良好,只是我不知道如何在默认绑定发生之前获得原始表单值以将其过滤出空字符串。
发布于 2011-01-12 02:44:52
哇,bindingContext有一个ModelName属性,它为你提供了前缀(用于列表项)。使用它,我可以获得原始的表单值:
...
var httpRequest = controllerContext.RequestContext.HttpContext.Request;
if (httpRequest.Form[bindingContext.ModelName + propertyDescriptor.Name] == "-" ||
httpRequest.Form[bindingContext.ModelName + propertyDescriptor.Name] == "N/a")
{
property.SetValue(model, null, null);
}
else
{
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
...https://stackoverflow.com/questions/4661287
复制相似问题