首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在绑定之前使用MVC ModelBinders过滤post值

在绑定之前使用MVC ModelBinders过滤post值
EN

Stack Overflow用户
提问于 2011-01-12 02:35:48
回答 1查看 1.7K关注 0票数 3

在绑定到MVC2中的POST数据之前,我需要过滤掉一些值。不幸的是,我不能改变客户端代码,它有时会传递"N/A“给要映射为十进制的表单值?类型。需要发生的是,如果"N/A“是POST值,则在绑定/验证之前将其清除。

我整个上午都在尝试使用一个扩展DefaultModelBinder的ModelBinder来让它正常工作:

代码语言:javascript
复制
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中,并且运行良好,只是我不知道如何在默认绑定发生之前获得原始表单值以将其过滤出空字符串。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-01-12 02:44:52

哇,bindingContext有一个ModelName属性,它为你提供了前缀(用于列表项)。使用它,我可以获得原始的表单值:

代码语言:javascript
复制
...
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);
}
...
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4661287

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档