If you define the following two properties on your model class this will crash with a NullReferenceException
during model binding:
public Customer Customer { get; private set; } //set in the action method
public bool Name => Customer.Name;
This is because Customer
is still null during model binding and ASP.NET MVC calls the getter for Name
.
The stack is:
System.ComponentModel.ReflectPropertyDescriptor.GetValue(Object component) +525
System.Web.Mvc.ModelMetadata.get_Model() +34
System.Web.Mvc.DataAnnotationsModelValidator.Validate(Object container) +151
System.Web.Mvc.<Validate>d__1.MoveNext() +387
System.Web.Mvc.DefaultModelBinder.OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext) +163
System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +83
System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +1754
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +460
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +137
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +982
System.Web.Mvc.<>c__DisplayClass22.<BeginExecuteCore>b__1e() +39
System.Web.Mvc.Async.AsyncResultWrapper.<.cctor>b__0(IAsyncResult asyncResult, Action action) +21
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +53
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +36
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +38
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +44
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +65
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +399
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +137
From the stack it looks like model validation is querying all getters. I'm not using model validation.
How can I deal with this situation? Can I make ASP.NET MVC not call all getters without any (apparent) reason?