I have been stumped with this one. Users will randomly get a null reference exception when performing a postback. It seems to me the problem is coming from the model binder and possibly the order at which the properties a parsed. Just wanted to see if anyone has any input? Ive not been able to duplicate will debugging, only happens in production randomly on postback.
Fairly Simple ViewModel:
public class ViewModel
{
public Load Load { get; set; }
public bool ReadOnly
{
get
{
return this.GetStatus(Load.Date);
}
}
public Load PrevLoad { get; set; }
private bool GetStatus(DateTime? date)
{
if (date != null)
{
if (date.Value.DayOfWeek == DayOfWeek.Monday)
date = date.Value.AddDays(-2);
return ((DateTime.Now.AbsoluteEnd() - date.Value.AbsoluteEnd()).TotalHours) <= -24 ? false : true;
}
else
return true;
}
}
StackTrace (Note I x'd out business sensitive namespaces):
System.Reflection.TargetInvocationException: Property accessor 'ReadOnly' on object
'XXX.XX.XXX.XXX.ViewModel' threw the following exception:'Object reference not set to an instance of an object.' ---> System.NullReferenceException: Object reference not set to an instance of an object.
at XXX.XX.XXX.ViewModels.ViewModel.get_ReadOnly()
--- End of inner exception stack trace ---
at System.ComponentModel.ReflectPropertyDescriptor.GetValue(Object component)
at System.Web.Mvc.DataAnnotationsModelValidator.<Validate>d__15.MoveNext()
at System.Web.Mvc.ModelValidator.CompositeModelValidator.<Validate>d__1.MoveNext()
at System.Web.Mvc.DefaultModelBinder.OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
at System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
at System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor)
at System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass1e.<BeginInvokeAction>b__16(AsyncCallback asyncCallback, Object asyncState)
When I pass null to this.GetStatus I get a different exception; So I know that cant be it.
Do you think this is throwing an exception because there technically isnt an instance of the ViewModel when modelBinding occurs and when attempting to access this.GetSatus it fails? That still wouldn't explain why this sometimes occurs.