Note that there are some explanatory texts on larger screens.

plurals
  1. POASP.NET MVC4 Model Binding Issue with Nullable DateTime property
    primarykey
    data
    text
    <p>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?". 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. It's just the optional datetimes (in this instance called "PublishStart" and "PublishEnd") that are failing to bind. The result that comes back from BindModel always has null values for these. The input in the form collection is always using the format "dd/MM/yyyy" for the datetime.</p> <p>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. </p> <p>Code I'm using is below. Does anyone have any ideas?</p> <pre><code>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); </code></pre> <p>Global ASAX has the following to set the default model binder</p> <pre><code>System.Web.Mvc.ModelBinders.Binders.DefaultBinder = new DefaultModelBinder(); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload