我正在为我的模型中的复杂类型创建一些自定义绑定器。我的模型由具有各自独立粘合剂的对象组成。我希望基础对象执行其脏工作,然后通过传递到标准的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();
}
谢谢,
贾斯汀
答案 0 :(得分:2)
我设法找到了解决方案。请随时评论其有效性。
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
Person person = new Person();
person.Name = bindingContext.ValueProvider.GetValue("Name").AttemptedValue
if (bindingContext.ModelName == String.Empty)
{
bindingContext.ModelName = "PhoneNumber";
}
else
{
bindingContext.ModelName = bindingContext.ModelName + ".PhoneNumber";
}
PhoneNumber phoneNumber = new PhoneNumber();
bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => phoneNumber, phoneNumber.GetType());
IModelBinder binder = ModelBinders.Binders[typeof(PhoneNumber)];
if (binder == null)
{
binder = ModelBinders.Binders.DefaultBinder;
}
person.PhoneNumber = binder.BindModel(controllerContext, bindingContext) as PhoneNumber;
return person;
}
以下是我所做的总结。
答案 1 :(得分:0)
您可以使用AutoMapper并在Action中处理复杂的模型构造,而不是编写活页夹。