简体   繁体   English

具有Nullable DateTime属性的ASP.NET MVC4模型绑定问题

[英]ASP.NET MVC4 Model Binding Issue with Nullable DateTime property

I'm experiencing an issue with model binding which is happening outside the context of a controller action. 我遇到模型绑定问题,该问题发生在控制器操作的上下文之外。 I'm using the following code to handle the binding, and it's working in almost all scenarios, however, it seems to fall over on any properties that are of type "DateTime?". 我正在使用以下代码来处理绑定,并且该绑定在几乎所有场景中都可以使用,但是,它似乎属于“ DateTime?”类型的所有属性。 Does anyone have any ideas? 有人有什么想法吗? In this instance TEntity is a POCO representing a blog post, so has a number of fields that are strings, longs etc. and these are all binding fine. 在这种情况下,TEntity是代表博客文章的POCO,因此具有许多字段,例如字符串,longs等,并且这些字段都具有很好的绑定性。 It's just the optional datetimes (in this instance called "PublishStart" and "PublishEnd") that are failing to bind. 只是绑定的可选日期时间(在这种情况下称为“ PublishStart”和“ PublishEnd”)。 The result that comes back from BindModel always has null values for these. 从BindModel返回的结果始终具有空值。 The input in the form collection is always using the format "dd/MM/yyyy" for the datetime. 表单集合中的输入对于日期时间始终使用格式“ dd / MM / yyyy”。

In stepping through the code in debug mode, I have tried using valueProvider.GetValue("PublishStart"), which doesn't throw any errors and shows what I'd expect for the RawValue, but I can't see how to get the value from that result to check whether it's parsed OK. 在调试模式下单步执行代码时,我尝试使用valueProvider.GetValue(“ PublishStart”),该方法不会引发任何错误并显示对RawValue的期望,但我看不到如何获取从该结果中获取值以检查其是否解析正常。

Code I'm using is below. 我正在使用的代码如下。 Does anyone have any ideas? 有人有什么想法吗?

var valueProvider = new NameValueCollectionValueProvider(formCollection, null);
var metadata = ModelMetadataProviders.Current.GetMetadataForType(null,
               typeof(TEntity));

var bindingContext = new ModelBindingContext
{
    ModelName = "",
    ValueProvider = valueProvider,
    ModelMetadata = metadata
    };

var controllerContext = new ControllerContext();
var binder = new DefaultModelBinder();

// act    
TEntity actual = (TEntity)binder.BindModel(controllerContext, bindingContext);

Global ASAX has the following to set the default model binder Global ASAX具有以下设置默认模型绑定程序的功能

System.Web.Mvc.ModelBinders.Binders.DefaultBinder = new DefaultModelBinder();

So a little digging yielded the answer here. 因此,稍加挖掘便得出了答案。 Turns out someone had added a custom model binder for DateTimes that was causing this to return null. 原来有人为DateTimes添加了一个自定义模型活页夹,这导致它返回null。 Moral of the story, look out for calls to Binders.Add. 讲故事的寓意,请注意对Binders.Add的调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM