从绑定中排除某些属性的最佳方法

时间:2015-06-06 06:15:10

标签: asp.net-mvc asp.net-mvc-5 model-binding

我的一个类有一些属性,我希望模型绑定器始终忽略它们。

目前我在动作方法中使用[Bind(Exclude ="")],如下所示:

public ActionResult Edit([Bind(Exclude = "prop1, prop2, prop3")] BusinessModel model)

此类已用于多种操作方法。我是否必须手动排除它们,或者有更好的方法?

我应该注意到这个特定的课程,它们是导航属性。

2 个答案:

答案 0 :(得分:2)

ramiramilu's answer很棒,但我想在其中添加一些细节。

最好使用新的BindingContext返回base.BindModel,这会排除要忽略的属性,而不是直接返回BusinessModel个对象。

这使得DefaultModelBinder的ModelState验证机制可以启动。

public class CustomDataBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType == typeof(BusinessModel))
        {
            BindAttribute bindAttribute = new BindAttribute
            {
                Exclude = "prop1, prop2, prop3"
            };

            // create new property filter where only properties which are not exluded in the above bindAttribute are bound
            Predicate<string> newPropertyFilter = propertyName => bindAttribute.IsPropertyAllowed(propertyName) && bindingContext.PropertyFilter(propertyName);         

            ModelBindingContext newBindingContext = new ModelBindingContext()
            {
                //bind default ModelMetaData
                ModelMetadata = bindingContext.ModelMetadata,

                //set to new property filter which exludes certain properties
                PropertyFilter = newPropertyFilter,

                //bind default ModelState
                ModelState = bindingContext.ModelState,

                //bind default ValueProvider
                ValueProvider = bindingContext.ValueProvider
            };
            return base.BindModel(controllerContext, newBindingContext);
        }
        else
        {
            return base.BindModel(controllerContext, bindingContext);
        }
    }
}

答案 1 :(得分:1)

使用集中式代码解决此问题的一种方法是覆盖BindModel的{​​{1}}并排除您不想绑定的属性。

DefaultModelBinder

然后在public class CustomDataBinder : DefaultModelBinder { public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { if (bindingContext.ModelType == typeof(BusinessModel)) { HttpRequestBase request = controllerContext.HttpContext.Request; string name = request.Form.Get("Name"); return new BusinessModel { Name = name }; } else { return base.BindModel(controllerContext, bindingContext); } } } 的{​​{1}}注册。

Global.asax

在上述情况下,我使用了Application_Start(),如下所述 -

ModelBinders.Binders.Add(typeof(BusinessModel), new CustomDataBinder());

为了测试,我创建了一个简单的视图 -

BusinessModel

当视图呈现时,我在两个编辑器中输入了一些数据 - enter image description here

当我点击“创建”按钮时,public class BusinessModel { public string prop1 { get; set; } public string Name { get; set; } } 编辑器中输入的值未绑定 -

enter image description here