本文介绍了当类型是可空不叫自定义模型绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有调用自定义结构的TimeOfDay 这是在这样的视图模型中:

I have a custom struct called TimeOfDay which is used in a view model like this:

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

我创建了一个叫做 TimeOfDayModelBinder 自定义模型粘结剂和Global.asax.cs中注册这样的:

I have created a custom model binder called TimeOfDayModelBinder and registered it in Global.asax.cs like this:

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

和一切伟大工程。但是,如果我改变我的视图模型这样:

And everything works great. However, if I change my view model to this:

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

我的自定义模型粘合剂不再叫。我知道,物业不再是一个类型的TimeOfDay,但可空这是不同的。因此,这是否意味着我应该补充的两倍我的自定义模型绑定在Global.asax.cs中是这样的:

My custom model binder is no longer called. I know that the property is no longer a type of TimeOfDay, but a Nullable which is different. So does this mean I should add my custom model binder twice in Global.asax.cs like this:

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

它的工作原理,但这里还有一些我不喜欢它。这真的有必要处理我喜欢的类型为可为空,或者是有什么我失踪?

It works, but there's just something I don't like about it. Is this really necessary to handle my type as nullable, or is there something I'm missing?

推荐答案

每@ LukeH的评论,现在看来,这是必要的。我想这是有道理的太多,因为的TimeOfDay 可空<的TimeOfDay> 确实是两种不同类型的CLR。所以我想我必须忍受它。 : - )

Per @LukeH's comment, it seems it is necessary. I guess that makes sense too, as TimeOfDay and Nullable<TimeOfDay> really is two different types in the CLR. So I guess I have to live with it. :-)

这篇关于当类型是可空不叫自定义模型绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-23 15:48