【问题标题】:Custom model binder not called when type is nullable类型可为空时未调用自定义模型绑定器
【发布时间】:2011-07-28 20:08:38
【问题描述】:

我有一个名为 TimeOfDay 的自定义结构,它用于这样的视图模型:

public class MyViewModel
{
  public TimeOfDay TimeOfDay { get; set; }
}

我创建了一个名为 TimeOfDayModelBinder 的自定义模型绑定器,并将其注册到 Global.asax.cs 中,如下所示:

ModelBinders.Binders.Add(typeof(TimeOfDay), new TimeOfDayModelBinder());

一切都很好。但是,如果我将视图模型更改为:

public class MyViewModel
{
  public TimeOfDay? TimeOfDay { get; set; } // Now nullable!
}

不再调用我的自定义模型绑定器。我知道该属性不再是 TimeOfDay 的类型,而是不同的 Nullable。那么这是否意味着我应该在 Global.asax.cs 中添加两次自定义模型绑定器,如下所示:

ModelBinders.Binders.Add(typeof(TimeOfDay), new TimeOfDayModelBinder());
ModelBinders.Binders.Add(typeof(TimeOfDay?), new TimeOfDayModelBinder());

它有效,但我不喜欢它。这真的有必要将我的类型处理为可为空的,还是我缺少什么?

【问题讨论】:

  • 我认为您没有遗漏任何东西。据我所知,这是标准的做法。
  • 你有没有想过这个问题?我有一个有点相似(但不完全)的问题。见my question
  • @notJim 我并没有真正深入研究,但结论是我需要添加两次模型绑定器。一次用于不可为空,一次用于可空,因为它实际上是 CLR 的两种不同类型。
  • 顺便说一下@LukeH,如果您对您的评论做出回答,我会接受它作为答案。 :-)

标签: c# asp.net-mvc-3 custom-model-binder


【解决方案1】:

这并不是您问题的真正答案,而是另一种解决方案。可能会有更好的...

在 MVC3 中,您可以创建 IModelBinderProvider。实现将是这样的:

public class TimeOfDayModelBinderProvider : IModelBinderProvider
{
    public IModelBinder GetBinder(Type modelType)
    {
          if(modelType == typeof(TimeOfDay) || modelType == typeof(TimeOfDay?))
            {
                 return  new TimeOfDayModelBinder();
            } 
           return null;
    }
}

您需要在 DependencyResolver/IOC 容器中注册它执行此操作(在 Global.asax - 应用启动):

ModelBinderProviders.BinderProviders.Add(new TimeOfDayModelBinderProvider());

【讨论】:

  • +1 很有趣,很高兴知道。但就我而言,我认为它会使事情复杂化而不是简化它。不过还是谢谢你。 :-)
【解决方案2】:

根据@LukeH 的评论,这似乎是必要的。我想这也是有道理的,因为 TimeOfDayNullable<TimeOfDay> 在 CLR 中确实是两种不同的类型。所以我想我必须忍受它。 :-)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-22
    • 2011-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-07
    • 2012-07-31
    相关资源
    最近更新 更多