Monday, February 18, 2013

ASP.NET MVC Error No Parameterless Constructor Defined For This Object

If you see following error when developing ASP.NET MVC application, that means one of the model class or any type of a complex model's properties does not have public default constructor.

No parameterless constructor defined for this object.
[MissingMethodException: No parameterless constructor defined for this object.]
   System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
   System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +113
   System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +232
   System.Activator.CreateInstance(Type type, Boolean nonPublic) +83
   System.Activator.CreateInstance(Type type) +6
   System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)

Solution to this problem, is to identify which type does not have the public default constructor or default constructor is NOT marked as public. 

You can either look at the source code to find out.  Or if you have ASP.NET MVC source code available to debug through, put a break point at first line of DefaultModelBinder.cs, it will tell you which type.
        protected virtual object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
        {
            Type typeToCreate = modelType;
 
For how to debug ASP.NET MVC source code, please look at my blog at http://luchen1021.blogspot.com/2013/02/debug-aspnet-mvc-4-source-code.html

No comments:

Post a Comment