[英]Register a custom model binder in MVC 4
In MVC 3, I created custom model binders by creating a new class that implemented Systen.Web.Mvc.IModelBinder
, and then registered it inside Global.asax.cs
and inside Application_Start()
using ModelBinders.Binders.Add(typeof(sometype), new MyModelBinder());
在MVC 3中,我通过创建一个实现了
Systen.Web.Mvc.IModelBinder
的新类来创建自定义模型绑定Systen.Web.Mvc.IModelBinder
,然后使用ModelBinders.Binders.Add(typeof(sometype), new MyModelBinder());
在Global.asax.cs
和Application_Start()
内部注册它。 ModelBinders.Binders.Add(typeof(sometype), new MyModelBinder());
In MVC 4 I understand that you are supposed to use System.Web.Http.ModelBinding.IModelBinder
to implement model binders. 在MVC 4中,我了解您应该使用
System.Web.Http.ModelBinding.IModelBinder
来实现模型绑定器。
So I have two questions: 所以我有两个问题:
Why are we supposed to use the model binder from System.Web.Http.ModelBinding
instead of the one from Systen.Web.Mvc
? 为什么我们应该使用
System.Web.Http.ModelBinding
的模型绑定器而不是Systen.Web.Mvc
的模型绑定Systen.Web.Mvc
? I don't see it is listed as deprecated anywhere, so what is the problem with the old one? 我没有看到它在任何地方被列为已弃用,那么旧版本的问题是什么?
If I implement my model binder from the System.Web.Http.ModelBinding.IModelBinder
, how do I register it inside my application so it will actually be used? 如果我从
System.Web.Http.ModelBinding.IModelBinder
实现我的模型绑定器,我如何在我的应用程序中注册它,以便实际使用它?
You can register your model binder in the same way(in the Global.asax.cs) and you can also use the System.Web.Mvc.IModelBinder
interface. 您可以以相同的方式注册模型绑定器(在Global.asax.cs中),也可以使用
System.Web.Mvc.IModelBinder
接口。
However, the System.Web.Http namespace is basically for the ASP.NET MVC Web API(ie for building web services). 但是,System.Web.Http命名空间基本上用于ASP.NET MVC Web API(即用于构建Web服务)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.