我正在为我的模型中的复杂类型创建一些自定义绑定器。我的模型由具有自己单独的活页夹的对象组成。我希望基础对象完成其肮脏的工作,然后通过传递给标准 ModelBinder 路由来填充它封装的复杂对象。我该怎么做呢?
出于说明目的,我创建了一个非常简单的示例。
假设我的模型包含这些对象。
public class Person
{
public string Name {get; set;}
public PhoneNumber PhoneNumber {get; set;}
}
public class PhoneNumber
{
public string AreaCode {get; set;}
public string LocalNumber {get; set;}
}
对于这些模型中的每一个,我都有以下活页夹。并不是说 PersonBinder 需要填充 PhoneNumber 但不想复制 PhoneNumber 活页夹中的代码。它如何委托给标准的 Binder 路由?
public class PersonBinder: IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
Person person = new Person();
person.Name = bindingContext.ValueProvider.GetValue(String.Format("{0}.{1}", bindingContext.ModelName, "Name")).AttemptedValue
// This is where I'd like to have the PhoneNumber object use binding from another customer ModelBinder.
// Of course the bindingContext.ModelName should be updated to its current value + "PhoneNumber"
person.PhoneNumber = ???; // I don't want to explicitly call the PhoneNumberBinder it should go through standard Binding routing. (ie. ModelBinders.Binders[typeof(PhoneNumber)] = new PhoneNumberBinder();)
return person;
}
}
public class PhoneNumberBinder: IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
PhoneNumber phoneNumber = new PhoneNumber();
phoneNumber.AreaCode = bindingContext.ValueProvider.GetValue(String.Format("{0}.{1}", bindingContext.ModelName, "AreaCode")).AttemptedValue
phoneNumber.LocalNumber = bindingContext.ValueProvider.GetValue(String.Format("{0}.{1}", bindingContext.ModelName, "LocalNumber")).AttemptedValue
return phoneNumber;
}
}
当然,我已经在 Global.asax.cs 文件中注册了我的 ModelBinders。
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
ModelBinders.Binders[typeof(Person)] = new PersonBinder();
ModelBinders.Binders[typeof(PhoneNumber)] = new PhoneNumberBinder();
}
谢谢,
贾斯汀