ASP.NET MVC: No parameterless constructor defined for this object
Asked Answered
C

28

187
Server Error in '/' Application.
--------------------------------------------------------------------------------

No parameterless constructor defined for this object. 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.MissingMethodException: No parameterless constructor defined for this object.

Source Error: 


Line 16:             HttpContext.Current.RewritePath(Request.ApplicationPath, false);
Line 17:             IHttpHandler httpHandler = new MvcHttpHandler();
Line 18:             httpHandler.ProcessRequest(HttpContext.Current);
Line 19:             HttpContext.Current.RewritePath(originalPath, false);
Line 20:         }

I was following Steven Sanderson's 'Pro ASP.NET MVC Framework' book. On page 132, in accordance with the author's recommendation, I downloaded the ASP.NET MVC Futures assembly, and added it to my MVC project. [Note: This could be a red herring.]

After this, I could no longer load my project. The above error stopped me cold.

My question is not, "Could you help me fix my code?"

Instead, I'd like to know more generally:

  • How should I troubleshoot this issue?
  • What should I be looking for?
  • What might the root cause be?

It seems like I should understand routing and controllers at a deeper level than I do now.

Coopery answered 31/8, 2009 at 1:45 Comment(0)
S
240

I just had a similar problem. The same exception occurs when a Model has no parameterless constructor.

The call stack was figuring a method responsible for creating a new instance of a model.

System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)


Here is a sample:

public class MyController : Controller
{
    public ActionResult Action(MyModel model)
    {

    }
}

public class MyModel
{
    public MyModel(IHelper helper) // MVC cannot call that
    {
        // ...
    }

    public MyModel() // MVC can call that
    {
    }
}
Skinned answered 1/9, 2010 at 21:46 Comment(8)
When POSTing JSON data to my action I was getting a similar error. It turns out my model which it is attempting to bind to does not have a parameterless constructor!Acclimate
NB: I only have this problem (no parameterless bla bla...) during serialization if I define a constructor, and not a parameterless contructor. I mean, in this example, if you delete the constructor you defined ( public MyModel(IHelper helper) {} ) the problem disappears... so everytime you create a constructor, you have to create a parameterless one... I can understand that like: once you start defined a constructor, the system does not take the risk to create 'default objects' because it does not know if it makes sense... something like that.Statius
Tuples... maybe for some other people that come here: if you have just Tuples (like Tuple<string, string> data; ) in your class, serialization will be ok (because I encountered this prob during JSON serialization)... but if you use something like List<Tuple<string, string>> data; you'll start having the 'no parameterless contructor' error. Because .Net can't/don't create Tuples (I have no ref for that but Tuple<string, string> data = new Tuple<string,string>(); won't compile... while Tuple<string, string> data = new Tuple<string,string>("", ""); is ok.Statius
Yeah, but how do you add a parameterless constructor to a class that has dependencies and you want to inject them in the constructor? That is the part of the problem I don't get ...Abecedary
@ToaoG your dependency injection library should provide you a way to select the "injection constructor". Btw, having dependency injection in viewmodels looks odd.Skinned
Literally just lost about 2 hours to this - I thought it was something to do with my Routes!!!! Thanks.Korwun
@Rick always look at the stack trace. It shows you where stuff went wrong.Skinned
I am getting this problem in Controller, not in Model! What should I do there then?Doggett
I
93

This can also be caused if your Model is using a SelectList, as this has no parameterless constructor:

public class MyViewModel
{
    public SelectList Contacts { get;set; }
}

You'll need to refactor your model to do it a different way if this is the cause. So using an IEnumerable<Contact> and writing an extension method that creates the drop down list with the different property definitions:

public class MyViewModel
{
    public Contact SelectedContact { get;set; }
    public IEnumerable<Contact> Contacts { get;set; }
}

public static MvcHtmlString DropDownListForContacts(this HtmlHelper helper, IEnumerable<Contact> contacts, string name, Contact selectedContact)
{
    // Create a List<SelectListItem>, populate it, return DropDownList(..)
}

Or you can use the @Mark and @krilovich approach, just need replace SelectList to IEnumerable, it's works with MultiSelectList too.

 public class MyViewModel
    {
        public Contact SelectedContact { get;set; }
        public IEnumerable<SelectListItem> Contacts { get;set; }
    }
Illuminate answered 21/10, 2011 at 12:39 Comment(8)
I wasted so much time on this... and had to turn my helper function that was returning a SelectList into one that would return a List<SelectListItem>....blargWretch
You can use IEnumerable<SelectListItem> and instantiate them in your constructor as new List<SelectListItem>()Aret
Thank you this was extremely helpful!Worrell
Still valid 5 years later. Thanks!Hackworth
I ran into this exact same problem but instead with a ReadOnlyCollectionVeiling
This solved my issue on the front end. But I cannot seem to get the controller to receive the data.Unionize
This should never be a problem. The SelectList Contacts property will not be initialized therefore a constructor is never called (unless of course you did something crazy like try to pass back name/value pairs for each SelectListItem in the collection by generating inputs for them.Gardia
It was MultiSelectList that caused me problems. Changed it to IEnumerable<SelectListItem>. Thank you!Umbrella
R
25

You need the action that corresponds to the controller to not have a parameter.

Looks like for the controller / action combination you have:

public ActionResult Action(int parameter)
{

}

but you need

public ActionResult Action()
{

}

Also, check out Phil Haack's Route Debugger to troubleshoot routes.

Result answered 31/8, 2009 at 1:49 Comment(3)
The exception is related to the Constructor, not the action method.Phyla
@Logrythmik. The reported exception is for the constructor, but the problem is in the action method. I had a class and action method which were working, then added a parameter to the action method, and got this error. An alternative solution is to provide a value for the parameter. Or make the parameter optional - this should work when the controller's in C#, but it didn't for me with F#Fetishist
Also, if you're doing something like @Html.Action("SomeAction", new { myParameter = "42" }), make sure that the name of the parameter in your Html.Action call matches the name of the parameter defined in your action method!Bithia
O
22

By default, MVC Controllers require a default constructor with no parameters. The simplest would be to make a default constructor that calls the one with parameters:

public MyController() : this(new Helper()) {
}

public MyController(IHelper helper) {
  this.helper = helper;
}

However, you can override this functionality by rolling your own ControllerFactory. This way you can tell MVC that when you are creating a MyController give it an instance of Helper.

This allows you to use Dependency Injection frameworks with MVC, and really decouple everything. A good example of this is over at the StructureMap website. The whole quickstart is good, and he gets specific to MVC towards the bottom at "Auto Wiring".

Observation answered 31/8, 2009 at 1:54 Comment(2)
I don't think this is the correct answer, @swilliams. The key here is the part: defined for this object. That's a crap error message that is actually hinting at the INPUT MODEL(s) passed in cannot be created. So if you have an input model that has no parameterless constructor, then you get this error. Very easy to think it was related to the CONTROLLER constructor. But it's not.Barbur
It is a crap message, that will have you on a wild goose chase if it wasn't for responses like these. Thanks to this answer and the response above, I was able to get things squared away. I guess it's a matter of not understanding fully what the binder is doing behind the scenes. I figured it would just set each property but for some reason it's calling the get before setting when posting as well. So because I overloaded my constructor and had to compensate with a parameter less constructor I had to account for nulls one some of my property gets, which was also unexpected.Gudrunguelderrose
R
22

This error also occurs when using an IDependencyResolver, such as when using an IoC container, and the dependency resolver returns null. In this case ASP.NET MVC 3 defaults to using the DefaultControllerActivator to create the object. If the object being created does not have a public no-args constructor an exception will then be thrown any time the provided dependency resolver has returned null.

Here's one such stack trace:

[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) +98
   System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) +241
   System.Activator.CreateInstance(Type type, Boolean nonPublic) +69
   System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +67

[InvalidOperationException: An error occurred when trying to create a controller of type 'My.Namespace.MyController'. Make sure that the controller has a parameterless public constructor.]
   System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +182
   System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +80
   System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +74
   System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +232
   System.Web.Mvc.<>c__DisplayClass6.<BeginProcessRequest>b__2() +49
   System.Web.Mvc.<>c__DisplayClassb`1.<ProcessInApplicationTrust>b__a() +13
   System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
   System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
   System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Func`1 func) +124
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +98
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8963444
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
Romito answered 3/10, 2011 at 21:19 Comment(3)
This caused my issue: My dependency resolver was unable to construct my controller because of an exception. It was swallowed by the resolver, returned null and the MVC framework switched to the default controller activator resulting in the error described.Honey
@jmona789 Check if you have set all your injected dependencies in your Global.asax.Mam
This was my issue. I still had the dependency resolver in place when making a demo of my project and I needed to remove it for the demo!Fortuitism
H
14

You can get this exception at many different places in the MVC framework (e.g. it can't create the controller, or it can't create a model to give that controller).

The only easy way I've found to diagnose this problem is to override MVC as close to the exception as possible with your own code. Then your code will break inside Visual Studio when this exception occurs, and you can read the Type causing the problem from the stack trace.

This seems like a horrible way to approach this problem, but it's very fast, and very consistent.

For example, if this error is occurring inside the MVC DefaultModelBinder (which you will know by checking the stack trace), then replace the DefaultModelBinder with this code:

public class MyDefaultModelBinder : System.Web.Mvc.DefaultModelBinder
{
    protected override object CreateModel(System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext, Type modelType)
    {
        return base.CreateModel(controllerContext, bindingContext, modelType);
    }
}

And update your Global.asax.cs:

public class MvcApplication : System.Web.HttpApplication
{
...
    protected void Application_Start(object sender, EventArgs e)
    {
        ModelBinders.Binders.DefaultBinder = new MyDefaultModelBinder();
    }
}

Now the next time you get that exception, Visual Studio will stop inside your MyDefaultModelBinder class, and you can check the "modelType" property to see what type caused the problem.

The example above works for when you get the "No parameterless constructor defined for this object" exception during model binding, only. But similar code can be written for other extension points in MVC (e.g. controller construction).

Hartzell answered 8/3, 2013 at 14:31 Comment(2)
That's what I was thinking of doing for my problem.Euthenics
Wish I could upvote this more. Saved me more than a few minutes of my time.Unattached
S
9

I got the same error, the culprit in my case was the constructor which was neither public nor private.

No parameterless constructor defined for this object.

Exception Details: System.MissingMethodException: No parameterless constructor defined for this object.

Repro code: Make sure the constructor has public before it.

public class Chuchi()
{
     Chuchi()    // The problem is this line. Public is missing
     {
         // initialization
         name="Tom Hanks";
     }

    public string name
    {
        get;
        set;
    }
}
Slalom answered 14/8, 2013 at 18:40 Comment(2)
Just as a note, lacking access modifiers on a constructor default to "internal" in the compiler.Kazimir
putting there "private" modifier will not solve the problem.Chivalrous
W
7

First video on http://tekpub.com/conferences/mvcconf

47:10 minutes in show the error and shows how to override the default ControllerFactory. I.e. to create structure map controller factory.

Basically, you are probably trying to implement dependency injection??

The problem is that is the interface dependency.

Wyon answered 7/2, 2011 at 11:13 Comment(1)
And you can get the StructureMapControllerFactory class from MVC Storefront projectIntermediacy
I
6

I got the same error when:

Using a custom ModelView, both Actions (GET and POST) were passing the ModelView that contained two objects:

public ActionResult Add(int? categoryID)
{
    ...
    ProductViewModel productViewModel = new ProductViewModel(
            product,
            rootCategories
            );
    return View(productViewModel); 
}

And the POST also accepting the same model view:

[HttpPost]
[ValidateInput(false)]
public ActionResult Add(ProductModelView productModelView)
{...}

Problem was the View received the ModelView (needed both product and list of categories info), but after submitted was returning only the Product object, but as the POST Add expected a ProductModelView it passed a NULL but then the ProductModelView only constructor needed two parameters(Product, RootCategories), then it tried to find another constructor with no parameters for this NULL case then fails with "no parameterles..."

So, fixing the POST Add as follows correct the problem:

[HttpPost]
[ValidateInput(false)]
public ActionResult Add(Product product)
{...}

Hope this can help somebody (I spent almost half day to find this out!).

Impress answered 13/10, 2010 at 14:15 Comment(3)
Nestor, this is enlightening and seems correct. But why is the View returning a different object then it is receiving, i.e. a Product object and not the ProductViewModel?Recreant
Oh, this was specific for my case, as I only need keep data for Products, the RootCategories was passed to the view only to print out, no input was done on it, so their values (RootCategories) were not kept in the <input> or anywhere else. Shall I need keep same ViewModel I would persist using the form <input>, the view data or something else.Impress
GilShalit, today I found an answer (sorry Im slow!), looking at HTML rendered I saw the input take the name of [ObjectName].[Property], but there is not trace of original ViewModel, so you can only retrieve each individual object inside the ViewModel, but not the complete ViewModel itself. Example:, if your ProductViewModel vm has inside objects Product p and Category c, then your GET controller sends one model vm to the View, then you POST controller can only accept parameters like (Product p, Category c), but not the vm... if I'm wrong would appreciate some feedback.Impress
R
5

The same for me. My problem appeared because i forgot that my base model class already has property with the name which was defined in the view.

public class CTX : DbContext {  // context with domain models
    public DbSet<Products> Products { get; set; }  // "Products" is the source property
    public CTX() : base("Entities") {}
}

public class BaseModel : CTX { ... }
public class ProductModel : BaseModel { ... }
public class OrderIndexModel : OrderModel  { ... }

... and controller processing model :

[HttpPost]
[ValidateInput(false)]
public ActionResult Index(OrderIndexModel order) { ... }

Nothing special, right? But then i define the view ...

<div class="dataItem">
    <%=Html.Label("Products")%>
    <%=Html.Hidden("Products", Model.index)%>   // I FORGOT THAT I ALREADY HAVE PROPERTY CALLED "Products"
    <%=Html.DropDownList("ProductList", Model.products)%>
    <%=Html.ActionLink("Delete", "D")%>
</div>

... which causes "Parameterless constructor" error on POST request.

Hope that helps.

Restrainer answered 31/8, 2011 at 10:20 Comment(0)
S
5

I had a similar problem, and basically the point is that there are some arguments in the action method that were not supplied by the Model Binding process, (and in other words these fields were not submitted by the submitting page).

This problem will come up even if all arguments but one are supplied, and even if the one missing is a nullable type.

The problem might also be a result of a typo, in which the name of the argument and name of the form field will not be identical.

The solution is to 1) verify that the names match up 2) provide a default value for the argument 3) or provide another action method without this argument.

Sidwel answered 13/8, 2012 at 18:24 Comment(1)
Thanks @yo hal, your answer turned out to be the one that solved my particular instance of this error. The error message the framework spits out happens to be the least useful error message ever in this instance.Beverage
H
4

I had this problem as well and thought I'd share since I can't find my problem above.

This was my code

return RedirectToAction("Overview", model.Id);

Calling this ActionResult:

public ActionResult Overview(int id)

I assumed it would be smart enough to figure out that the value I pass it is the id paramter for Overview, but it's not. This fixed it:

return RedirectToAction("Overview", new {id = model.Id});

Himalayas answered 8/11, 2011 at 8:40 Comment(0)
K
4

I got same exception due to there was no parameterless public contructor

Code was like this:

public class HomeController : Controller
{        
    private HomeController()
    {
        _repo = new Repository();
    }

changed to

 public class HomeController : Controller
{        
    public HomeController()
    {
        _repo = new Repository();
    }

problem resolved to me.

Kinelski answered 15/1, 2014 at 20:33 Comment(1)
I was having the same problem when using a protected constructor in a base class - seems an obvious solution now!Wrongful
B
4

All of the answers say to create a parameters less constructor which isn't ideal if you don't want any other devs using it and only the model binder.

The attribute [Obsolete("For model binding only", true)] above a public constructor will throw a compiler error if another dev tries to use this. Took me ages to find this, hope it helps someone.

Bobbi answered 13/7, 2016 at 1:6 Comment(1)
Perfect - adding this attribute allowed the MVC model binding to work at runtime, and setting the attribute's boolean parameter to true prevented (at compile time) any attempt to instantiate the parameterless constructor. Best answer here.Photolithography
W
3

I got this error. I was using interfaces in my constructor and my dependency resolver wasn't able to resolve, when i registered it then the error went away.

Whiffet answered 29/8, 2016 at 13:15 Comment(1)
If you have a new question, please post it as such. This should have been either a comment or a new question as it does not attempt to answer the problem.Fulsome
R
2

I had the same problem...

If your using a interface to decouple your connection against your DbContext (like me) you can use structuremap.mvc (3 or 4 - nudget package) to be able to use a constructure in your controller class. This will give you a DependencyResolution folder. Just change the commented line with your For< InterfaceClass >() and to Use< DbContextClass >().

Regenerative answered 3/1, 2013 at 10:30 Comment(0)
P
2

While this may be obvious to some, the culprit of this error for me was my MVC method was binding to a model that contained a property of type Tuple<>. Tuple<> has no parameterless constructor.

Platas answered 8/5, 2013 at 19:10 Comment(0)
F
2

This type error may come up due to missing dependency injector/resolver container and/or missing the bindings

  1. Add Dependency injector to your project using NugetPacketManager (Unity, Ninject or whichever you like)
  2. Add binding(s) for interface and concrete implementation for the classes

UnityMConfig.cs

using System;
using Unity;
using <your_namespace for the interfaces and concrete classes>

namespace <your_namespace>
{
    public static class UnityConfig
    {
        private static Lazy<IUnityContainer> container =
            new Lazy<IUnityContainer>(() =>
            {
                var container = new UnityContainer();
                RegisterTypes(container);
                return container;
            });

        public static IUnityContainer Container => container.Value;

        public static void RegisterTypes(IUnityContainer container)
        {
            container.RegisterType <IInterfaceClassName, ConcreteImplementationOfInterface> ();
        }
    }
}

UnityMvcActivator.cs

using System.Linq;
using System.Web.Mvc;
using Unity.AspNet.Mvc;

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(xxxx.UnityMvcActivator), nameof(xxxx.UnityMvcActivator.Start))]
[assembly: WebActivatorEx.ApplicationShutdownMethod(typeof(xxxx.UnityMvcActivator), nameof(xxxx.UnityMvcActivator.Shutdown))]

namespace <your_namespace>
{
    public static class UnityMvcActivator
    {
        public static void Start()
        {
            FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
            FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(UnityConfig.Container));
            DependencyResolver.SetResolver(new UnityDependencyResolver(UnityConfig.Container));
        }
        public static void Shutdown()
        {
            UnityConfig.Container.Dispose();
        }
    }
}
Fullrigged answered 26/7, 2021 at 4:23 Comment(0)
A
1

I had same problem but later found adding any new interface and corresponding class requires it to be registered under Initializable Module for dependency injection. In my case it was inside code as follows:

[InitializableModule]
[ModuleDependency(typeof(EPiServer.Web.InitializationModule))]
public class DependencyResolverInitialization : IConfigurableModule
{

    public void ConfigureContainer(ServiceConfigurationContext context)
    {
        context.Container.Configure(ConfigureContainer);
        var structureMapDependencyResolver = new StructureMapDependencyResolver(context.Container);
        DependencyResolver.SetResolver(structureMapDependencyResolver);
        GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerActivator), structureMapDependencyResolver);
    }

    private void ConfigureContainer(ConfigurationExpression container)
    {
        container.For<IAppSettingService>().Use<AppSettingService>();
        container.For<ISiteSettingService>().Use<SiteSettingService>();
        container.For<IBreadcrumbBuilder>().Use<BreadcrumbBuilder>();
        container.For<IFilterContentService>().Use<FilterContentService>().Singleton();
        container.For<IDependecyFactoryResolver>().Use<DependecyFactoryResolver>();
        container.For<IUserService>().Use<UserService>();
        container.For<IGalleryVmFactory>().Use<GalleryVmFactory>();
        container.For<ILanguageService>().Use<LanguageService>();
        container.For<ILanguageBranchRepository>().Use<LanguageBranchRepository>();
        container.For<ICacheService>().Use<CacheService>(); 
        container.For<ISearchService>().Use<SearchService>();
        container.For<IReflectionService>().Use<ReflectionService>();
        container.For<ILocalizationService>().Use<LocalizationService>();
        container.For<IBookingFormService>().Use<BookingFormService>();
        container.For<IGeoService>().Use<GeoService>();
        container.For<ILocationService>().Use<LocationService>();
        RegisterEnterpriseAPIClient(container);
    }

   public void Initialize(InitializationEngine context)
    {
    }

    public void Uninitialize(InitializationEngine context)
    {
    }

    public void Preload(string[] parameters)
    {
    }
}

}

Addictive answered 17/7, 2017 at 11:38 Comment(0)
N
1

In my case, my class had the [Serializable] attribute.

You are required to have a constructor that takes no parameters if your class is [Serializable]

Nucleoplasm answered 1/11, 2018 at 16:48 Comment(0)
T
1

I added a parameterless constructor to the model inside of DOMAIN Folder, and the problem is solved.

enter image description here

 public User()
        {

        }
Tyrannize answered 30/6, 2020 at 7:57 Comment(0)
C
1

I got the same issue when trying to Add-Migration on the DbContext class.

First I got the error: Unable to create an object of type 'ContextDb'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

Which made me add the interface IDesignTimeDbContextFactory and implement it's function:

public ContextDb CreateDbContext(string[] args)
    {
        var optionBuilder = new DbContextOptionsBuilder<ContextDb>();
        optionBuilder.UseSqlServer("Server_connection");
        return new ContextDb(optionBuilder.Options);
    }

At this time the error No parameterless constructor defined for type 'LibraryContext.ContextDb' happened when trying to Add-Migration again. Which occured due to the new instance of the ContextDb created in CreateDbContext(). To fix this I just added an empty constructor:

public ContextDb()     
    {
    }
Causation answered 16/4, 2022 at 1:36 Comment(0)
G
0

This error started for me when I added a new way to instantiate a class.

Example:

    public class myClass
    {
         public string id{ get; set; }
         public List<string> myList{get; set;}

         // error happened after I added this
         public myClass(string id, List<string> lst)
         {
             this.id= id;
             this.myList= lst;
         }
     }

The error was resolved when I added when I made this change, adding a parameterless constructor. I believe the compiler creates a parameterless constuctor by default but if you add your own then you must explicitly create it.

    public class myClass
    {
         public string id{ get; set; }
         public List<string> myList{get; set;}

         // error doesn't happen when I add this
         public myClass() { }

         // error happened after I added this, but no longer happens after adding above
         public myClass(string id, List<string> lst)
         {
             this.id= id;
             this.myList= lst;
         }
     }
Granulation answered 12/6, 2014 at 20:34 Comment(0)
A
0

I'd added a DropDownList to my form, however in my case it wasn't (and wasn't intended to be) submitted with the form as it was outside of the <form></form> tags:

@Html.DropDownList("myField", Model.MyField)

As the Model contained the field for display only, this also caused the No parameterless constructor defined for this object error because the field wasn't submitted at all.

In this case I fixed it by adding an exclude binding:

public ActionResult Foo(int id, int? page, [Bind(Exclude = "MyField")]MyModel model)
Airglow answered 29/7, 2014 at 11:19 Comment(0)
A
0

This happened to me, and the results on this page were a good resource that led me in many directions, but I would like to add another possibility:

As stated in other replies, creating a constructor with parameters removes the implicit parameterless constructor, so you have to explicitly type it.

What was my problem was that a constructor with default parameters also triggered this exception.

Gives errors:

public CustomerWrapper(CustomerDto customer = null){...}

Works:

public CustomerWrapper(CustomerDto customer){...}
public CustomerWrapper():this(null){}
Association answered 22/7, 2015 at 14:52 Comment(0)
L
0

Most probably you might have parameterized constructor in your controller and whatever dependency resolver you are using is not able to resolve the dependency properly. You need to put break-point where the dependency resolver method is written and you will get the exact error in inner exception.

Layton answered 12/12, 2015 at 16:42 Comment(0)
B
0

I had the same problem.

Just Removed HttpFileCollectionBase files from Post Action method argument and added like HttpFileCollectionBase files = Request.Files; in method body.

Basketry answered 13/4, 2018 at 6:38 Comment(0)
L
-3

So I have gotten that message before as well, when doing an ajax call. So what it's basically asking for is a constructor in that model class that is being called by the contoller, doesn't have any parameter.

Here is an example

public class MyClass{

     public MyClass(){} // so here would be your parameterless constructor

 }
Lateritious answered 4/8, 2015 at 21:2 Comment(1)
I removed default constructor from model, this works for me.Sang

© 2022 - 2024 — McMap. All rights reserved.