ASP.NET MVC-接口类型上的自定义模型活页夹
-
24-10-2019 - |
题
我不确定是否期望此行为,但是当将绑定分配给接口类型时,自定义模型绑定似乎不起作用。有人尝试过吗?
public interface ISomeModel {}
public class SomeModel : ISomeModel {}
public class MvcApplication : HttpApplication {
protected void Application_Start(object sender, EventArgs e) {
ModelBinders.Binders[typeof(ISomeModel)] = new MyCustomModelBinder();
}
}
使用上述代码,当我绑定到类型的Somemodel模型时,Mycustombosportelbinder永远不会受到打击。但是,如果我更改上述代码并替代 typeof(ISomeModel)
为了 typeof(SomeModel)
并发布完全相同的mycustommodelbinder形式,称为预期。这看起来对吗?
编辑
在我最初提出这个问题后的一年后,我发现自己陷入了这种困境,现在我有了一个有效的解决方案。谢谢Matt Hidinger!
http://www.matthinger.com/archive/2011/08/16/an-inheritance-aware-modelbinderprovider-in-mvc-3.aspx
解决方案
我不确定它是否直接相关,但是是的,在使用模型绑定和接口时,您需要考虑一些事情...我遇到了默认模型粘合剂的类似问题,但是根据如何取决于如何取决于如何直接相关你在做事...
看看以下内容:ASP.NET MVC V2-调试模型绑定问题 - 错误? ASP.NET MVC V2-调试模型绑定问题 - 错误?
其他提示
我正在尝试这个问题,并提出了一种解决方案。我做了一个名为Interfacemodelbinder的课程:
public class InterfaceModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
ModelBindingContext context = new ModelBindingContext(bindingContext);
var item = Activator.CreateInstance(
Type.GetType(controllerContext.RequestContext.HttpContext.Request.Form["AssemblyQualifiedName"]));
Func<object> modelAccessor = () => item;
context.ModelMetadata = new ModelMetadata(new DataAnnotationsModelMetadataProvider(),
bindingContext.ModelMetadata.ContainerType, modelAccessor, item.GetType(), bindingContext.ModelName);
return base.BindModel(controllerContext, context);
}
}
我在application_start中注册的是:
ModelBinders.Binders.Add(typeof(IFormSubmission), new InterfaceModelBinder.Models.InterfaceModelBinder());
界面和具体实现看起来像这样:
public interface IFormSubmission
{
}
public class ContactForm : IFormSubmission
{
public string Name
{
get;
set;
}
public string Email
{
get;
set;
}
public string Comments
{
get;
set;
}
}
整个方法的唯一缺点(正如您可能已经收集的那样)是,我需要从某个地方获取AssemblyQualifyname,在此示例中,它被存储为客户端的隐藏字段,例如:
<%=Html.HiddenFor(m => m.GetType().AssemblyQualifiedName) %>
尽管我不确定将类型名称公开向客户的缺点值得失去这种方法的好处。这样的行动可以处理我的所有表格提交:
[HttpPost]
public ActionResult Process(IFormSubmission form)
{
if (ModelState.IsValid)
{
FormManager manager = new FormManager();
manager.Process(form);
}
//do whatever you want
}
对这种方法有什么想法吗?