![](/img/trans.png)
[英]Why can't I add my custom model binder in my global.asax folder?
[英]Why can't I register a custom model binder for a List<int>?
我有一个看起来像的动作
public ActionResult GetUsers(List<int> userIds) {//do stuff}
userId的列表可能会变得很长,因此我想使用Json.Net对其进行反序列化。 为此,我创建了一个IModelBinder实现,该实现对于其他对象也可以正常工作,但是永远不会被List调用。 IModelBind看起来像这样
public class JsonBinder : System.Web.Mvc.IModelBinder
{
public object BindModel(System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext)
{ //Do model binding stuff using Json.Net }
}
我在这行注册这个模型活页夹
ModelBinders.Binders.Add(typeof(List<int>), new JsonBinder());
但是,永远不会调用JsonBinder。 为什么是这样? 我应该使用ValueProvider吗?
在global.asax中添加以下事件(或将代码添加到现有的Application_BeginRequest处理程序中):
protected void Application_BeginRequest()
{
foreach (var type in ModelBinders.Binders.Keys)
{
System.Diagnostics.Trace.WriteLine(
String.Format("Binder for '{0}': '{1}'",
type.ToString(),
ModelBinders.Binders[type].ToString()));
}
}
然后,您可以在VS输出窗口中检查当前已注册哪些活页夹。 您可能会看到以下内容:
Binder for 'System.Web.HttpPostedFileBase': 'System.Web.Mvc.HttpPostedFileBaseModelBinder'
Binder for 'System.Byte[]': 'System.Web.Mvc.ByteArrayModelBinder'
Binder for 'System.Data.Linq.Binary': 'System.Web.Mvc.LinqBinaryModelBinder'
Binder for 'System.Threading.CancellationToken': 'System.Web.Mvc.CancellationTokenModelBinder'
您还可以检查是否有任何ModelBinderProvider
可以选择活页夹提供程序,因为选择使用哪种模型活页夹的顺序如下:
操作参数上的属性。 请参见ControllerActionInvoker类的 GetParameterValue方法
活页夹从IModelBinderProvider返回。 请参见ModelBinderDictionary类中的GetBinder方法
活页夹已在ModelBinders.Binders词典中全局注册。
在[ModelBinder()]
属性中为模型类型定义的Binder。
DefaultModelBinder。
使用类似的方法在BeginRequest事件中检查模型绑定程序提供程序:
foreach (var binderprovider in ModelBinderProviders.BinderProviders)
{
System.Diagnostics.Trace.WriteLine(String.Format("Binder for '{0}'", binderprovider.ToString()));
}
此外,您可以尝试通过nuget添加Glimpse ,因为其中一个选项卡提供了有关用于控制器操作中每个参数的模型绑定程序的信息。
希望这将帮助您找到未使用模型联编程序的原因。
您是否尝试过在action方法中使用ModelBinder属性?
public ActionResult GetUsers([ModelBinder(typeof(JsonBinder))] List<int> userIds)
参考: https : //msdn.microsoft.com/zh-cn/library/system.web.mvc.modelbinderattribute(v= vs.118) .aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.