问题描述
我创建在MVC应用程序自定义模型粘结剂,我想解析字符串枚举值,并将其分配到模型属性。我有它的工作覆盖 BindProperty
方法,但我也注意到有一个的SetProperty
方法。
I'm creating a custom model binder in an Mvc application and I want to parse a string to an enumeration value and assign it to the model property. I have got it working overriding the BindProperty
method, but I also noticed that there is a SetProperty
method.
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
{
switch (propertyDescriptor.Name)
{
case "EnumProperty":
BindEnumProperty(controllerContext, bindingContext);
break;
}
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
private static void BindEnumProperty(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var formValue = controllerContext.HttpContext.Request.Form["formValue"];
if (String.IsNullOrEmpty(formValue))
{
throw new ArgumentException();
}
var model = (MyModel)bindingContext.Model;
model.EnumProperty = (EnumType)Enum.Parse(typeof(EnumType), formValue);
}
我不知道有什么区别这两个和我是否以建议的方式这样做。
I’m not sure what the difference is between the two and whether I am doing this in the recommended way.
推荐答案
首先,BindProperty不是IModelBinder的一部分,但是,在DefaultModelBinder受保护的方法。您可以访问它只是如果你是子类的DefaultModelBinder。
First of all, BindProperty is not a part of IModelBinder but, a protected method in DefaultModelBinder. You can access it only if you are sub-classing the DefaultModelBinder.
以下几点应该回答你的问题:
The following points should answer your question:
- BindProperty使用IModelBinder
接口,它从变
的属性类型
PropertyDescriptor的说法。这个
让你自定义的注入
物业进入房地产
元数据。 - BindProperty正常
处理验证。它(还)调用
只有当SetProperty方法
新价值是有效的。
所以,如果你想适当的验证(使用注释属性),你必须明确地调用BindProperty。通过调用的SetProperty你绕过所有内置的验证机制。
So if you want proper validation (using the annotation attributes) you must definitely call BindProperty. By calling SetProperty you bypass all the built-in validation mechanisms.
您应该检查出的来源$ C $ C DefaultModelBinder在看到每个方法做什么,因为智能感知只提供有限的信息。
You should check out the source code of DefaultModelBinder the see what each method does, since the intellisense provides only limited information.
这篇关于是什么在IModelBinder BindProperty和setProperty之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!