在MVC2中的帖子数据绑定之前,我需要过滤一些值。不幸的是,我无法更改有时将“ n/a”传递给要映射到十进制的表单值的客户端代码?类型。需要发生的事情是,如果“ n/a”是在绑定/验证之前将其空白的。

我整个早晨都尝试使用扩展DefaultModelBinder的模型框来使其正常工作:

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并运行良好,我只是不知道如何握住原始形式值以在默认绑定发生之前将其过滤为空字符串。

有帮助吗?

解决方案

哇,bindingContext具有模型名属性,可为您提供前缀(适用于列表项目)。使用那使我可以获得原始形式的价值:

...
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);
}
...
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top