【发布时间】:2016-01-11 12:30:01
【问题描述】:
我正在使用 MVC.NET 5.2.3 并尝试将模型发布到模型包含多个接口的控制器。这会导致 .NET 抛出此异常:
无法创建接口的实例
我知道这是因为我在模型 (ITelephone) 中使用了接口。我的模型是这样的:
public class AddContactPersonForm
{
public ExternalContactDto ExternalContact { get; set; }
public OrganizationType OrganizationType { get; set; }
}
public class ExternalContactDto
{
public int? Id { get; set; }
public string Name { get; set; }
public string Title { get; set; }
public IList<ITelephone> TelephoneNumbers { get; set; }
}
public interface ITelephone
{
string TelephoneNumber { get; set; }
}
public class TelephoneDto : ITelephone
{
public string TelephoneNumber { get; set; }
}
如果我使用 TelephoneDto 类而不是 ITelephone 接口,它可以正常工作。
我知道我需要使用 ModelBinder,这很好。但是我真的只是想说modelbinder应该创建什么样的实例,而不是手动映射整个模型。
@jonathanconway 在这个问题中给出的答案与我想要做的很接近。
Custom model binder for a property
但我真的很想将它与简单地告诉 defaultbinder 用于特定接口的类型的简单性结合起来。与使用 KnownType 属性的方式相同。 defaultbinder 显然知道如何映射模型,只要它知道应该创建哪个类。
如何告诉 DefaultModelBinder 它应该使用什么类来反序列化接口然后绑定它?它目前崩溃,因为发布的模型 (AddContactPersonForm) 包含一个具有接口 ITelephone 的“复杂”模型 (ExternalContactDto)。
这是我目前得到的。
public class ContactPersonController : Controller
{
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddContactPerson([ModelBinder(typeof(InterfaceModelBinder))] AddContactPersonForm addContactPersonForm)
{
// Do something with the model.
return View(addContactPersonForm);
}
}
public class InterfaceModelBinder : DefaultModelBinder
{
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext,
PropertyDescriptor propertyDescriptor)
{
var propertyBinderAttribute = TryFindPropertyBinderAttribute(propertyDescriptor);
if (propertyBinderAttribute != null)
{
// Never occurs since the model is nested.
var type = propertyBinderAttribute.ActualType;
var model = Activator.CreateInstance(type);
bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, type);
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
return;
}
// Crashed here since because:
// Cannot create an instance of an interface. Object type 'NR.Delivery.Contract.Models.ITelephone'.
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
private InterfaceBinderAttribute TryFindPropertyBinderAttribute(PropertyDescriptor propertyDescriptor)
{
return propertyDescriptor.Attributes
.OfType<InterfaceBinderAttribute>()
.FirstOrDefault();
}
}
public class ExternalContactDto
{
public int? Id { get; set; }
public string Name { get; set; }
public string Title { get; set; }
[InterfaceBinder(typeof(List<TelephoneDto>))]
public IList<ITelephone> TelephoneNumbers { get; set; }
}
public class InterfaceBinderAttribute : Attribute
{
public Type ActualType { get; private set; }
public InterfaceBinderAttribute(Type actualType)
{
ActualType = actualType;
}
}
【问题讨论】:
-
那么你的问题到底是什么?
-
@AnupSharma,对不起。我编辑了问题并试图澄清我需要帮助的地方。
标签: c# asp.net-mvc model-binding