虽然 Charlino 的解决方案很聪明并且会起作用,但我个人不喜欢仅仅为此目的而用额外的属性“弄脏”我的域实体的想法。我想你已经有了答案:自定义模型绑定器。就像是:
public class S2kBoolAttribute : CustomModelBinderAttribute, IModelBinder
{
public override IModelBinder GetBinder()
{
return this;
}
public object BindModel( ControllerContext controllerContext, ModelBindingContext bindingContext )
{
ValueProviderResult result;
return bindingContext.ValueProvider.TryGetValue( bindingContext.ModelName, out result )
? (S2kBool)result.ConvertTo( typeof( bool ) )
: null;
}
}
然后你可以修改你的控制器动作看起来像:
public ActionResult Foo( [S2kBool]S2kBool myProperty ){
myClassInstance.MyProperty = myProperty;
SaveToLegacyDb(myClassInstance);
return RedirectToAction("Bar");
}
如果您在模型绑定器中投入更多的工作,您可以让它与全局注册的绑定器一起工作——但是我上面给您的实现应该可以在需要时用于挑选值。