u936293
u936293

Reputation: 16224

MVC: No parameterless constructor for this object

I know I can correct the problem by simply adding a parameterless constructor to the model, but I would like to understand why.

The standard MVC template in VS2013 has an error view in the Shared folder. It takes a HandleErrorInfo class as its model. This view is called directly from various places and there is no matching Error action defined.

I added an Error action intending to add logging:

public ActionResult Error(HandleErrorInfo model)
{
    //TODO! Log error
    return View(model);
}

This resulted in the No parameterless constructor defined for this object exception when I called:

return RedirectToAction("error", model);

The above pattern is everywhere in the project, and all the models I see also do not have a parameterless constructor. Why is it happening in this Error action?

Upvotes: 0

Views: 916

Answers (1)

user3559349
user3559349

Reputation:

When an ActionResult method is called, the DefaultModelBinder first initializes an instance of the model. Internally it uses Activator.CreateInstance<T>() static method. From the documentation, this will throw a MissingMethodException if

The type that is specified for T does not have a parameterless constructor.

HandleErrorInfo does not have a parameterless constructor, hence the exception

Upvotes: 1

Related Questions