Fun and Struggles with MVC – No Parameterless Constructor Defined

It’s taking a little while, but I’m starting to understand the magic behind model binding in MVC. It’s fairly simply to try it out while watching videos and tutorials that are out there; but when I applied it to our enterprise application with a fairly large collection of domain models that already exist, I had less than ideal results.

Here’s the struggle I was having…

The Problem

I have an entity called a SalesRep which has several properties including a few complex object properties such as EmailAddress , PersonName (struct), and Address (street1, street2, city, state, etc.) as well as many primitives.

I had both GET and POST Create actions defined in the SalesRepController as follows:

/// <summary>
/// Add a new sales rep.
/// </summary&rt;
/// <returns&rt;</returns&rt;
public ActionResult Create()
{
   return View(new SalesRep());
}

/// <summary>
/// Save a new sales rep.
/// </summary>
/// <param name="salesRep"></param>
/// <returns>If successful, the SalesRep/List/ View.  If not successful, the current SalesRep/Create/ view.</returns>
[HttpPost]
public ActionResult Create(SalesRep salesRep)
{
   var logic = new SalesLogic();
   logic.SaveSalesRep(ref salesRep);

   return RedirectToAction("List");
}

However, when calling the Create action on the SalesRepController, I would get the following Parameterless constructor error and could never even enter into a breakpoint.

No Parameterless Constructor Defined for this object

The Solution

After spending quite a bit of time experimenting and searching the internet, I couldn’t readily resolve the issue. Feeling as though I was never going to grasp MVC, and cursing the videos that looked so ridiculously easy, I spun up a new trivial sandbox project. I created new simplistic models, new controllers, and everything worked perfectly. So what made my old enterprise entity classes different? The answer was… the constructors.

As you can see in the above error message it is properly reporting that it could not find a parameterless constructor for the object; but which object? I had been looking at the SalesRep object and even the View and Controllers, but what I should have been looking at was the complex properties within the SalesRep as MVC recursively reflected all of the properties and created them with a parameterless constructor. In my case, we had an EmailAddress which specifies a single constructor:

public EmailAddress(string value) {
   //our code
}

It was while MVC was auto-magically wiring up the form elements to the email address object that the action came tumbling down.

A Simple Recreation

I’ve recreated this scenario using a simpler class slightly modified from Scott Allen’s pluralsight demo’s.

Below is a screenshot of my newly created Movie class which contains three properties; Name, Year, and Studio. Name and Year are both primitives, while Studio references another entity.

Movie Class

Here is the Studio class with the pertinent name parameter constructor only. There is no parameterless constructor in this class and because we have specified a constructor the default is overridden.

Studio Class

When we now reference this property within the Create View to allow for model binding we will encounter the error.

Movie View

We can correct this by adding a parameterless constructor in the Studio class and all is well again.

Catching up to MVC

Contrary to my nature, I’ve been reluctant to adopt the “latest and greatest” from Microsoft for the past twelve months or so. A good deal of my tech lag time has been due to my primary position leading an Oracle Enterprise Business Suite (EBS) project which has put me in the world of red, not blue. It’s been the unfamiliar – Oracle DB, Jdeveloper, and putty – that I’ve been working in more than anything made in Redmond lately. However, there is an equally valid reason – I’ve lost a bit of my Microsoft faith over the countless hours of podcasts, reading articles, and attending events which had left me completely unsure what Microsoft was doing (and questioning whether Microsoft knew as well). For quite a while it felt as though everything Microsoft created was tossed into the eco-system somewhat half-baked and what received the most buzz stuck. Perhaps this is Microsoft adopting some of the open source mentality that has been so hard on Microsoft in the past; perhaps it was simply to create a competitive nature internally at Microsoft; but to some critics, and even a handful of die-hard developers like myself, it seemed scattered and without direction.

There’s a bit more of a problem that I now understand more fully than when I was younger; time is not an infinite resource. Before I would jump whole-heartedly into a new technology learning with vigorous disregard of whether that technology would rise to the top or fall by the wayside. The cost was minimal; it only meant time away from things I probably shouldn’t be doing anyway.

Now that I have a daughter (as well as another on the way) and other family demands, I have to choose very carefully what my training time can go to. Should the focus be MVC, WP7, Silverlight, BizTalk (or gasp, Oracle SOA Suite), Entity Framework, jQuery, HTML5/CSS3, Azure, Denali, Kinect SDK, or any of the now vast array of Microsoft offerings available to developers?

So, as I’ve found myself occupied in other technologies, I rode the fence to see what shook out. It looks like Microsoft is finding their groove again and it’s time to brush aside the fallout and introduce the winner(s).

Welcome MVC to My Toolbox

As most of you know, MVC as a pattern has been around for quite a while. It is this reason that I originally waited to see if Microsoft’s implementation would survive or if the community would look to past MVC frameworks and decide to go back to something from the open source community or an established Java MVC implementation that would be ported over.

Obviously, that does not appear to be the case and Microsoft’s MVC implementation has been a huge success.

So now it’s time to get to work. I’ll be periodically posting about my learning process with MVC if any other developers are interested. There is a huge list of resources now available for MVC and as I post (or you comment), I will try and steer developers to what I consider the most useful.

Disclaimer and decisions made about the example material

Please note that there is still a plethora of examples showing simple MVC apps which I am intentionally choosing to not use in these blog posts. I am starting with a quite large project to accurately compare MVC to “the real world of enterprise applications”. I’ve also decided to employ logic and models via a service layer instead of directly in the MVC project. P.S. – way to go MVC for allowing this, it should be played up more in examples!

Also, in case you didn’t pick up on this earlier, but this is a learning journey for me with MVC – I am by no means an expert… yet.

Without further ado, here are my notes from the first foray into MVC with an enterprise application.

Project Orange (the anti-apple)

It’s not important what this project is, but it is intended to have multiple tiers where the web tier will be MVC. Let’s look at the setup of the projects:

Project Orange Projects

BusinessDataLogic is a combined BLL and DAL using entity framework.
Models are the business entities and DTO’s.
Services are WCF services which wrap the business logic and expose DTO’s.
Utilities are just helper classes that are common throughout the tiers (extension methods, etc.)
Web is MVC.

MVC Presentation Tier

Let’s take a closer look at the web application and the asset structure:

Project Orange MVC

As you can see, I’ve added a service reference for my WCF Inventory service. I’ve also added an ItemController and a corresponding View directory for Item.

I’ve added one new method within the ItemController for searching:

//
// GET: /Item/Search/had

public ActionResult Search(string text)
{
   var client = new InventoryService.InventoryClient();
   var items = client.SearchItems(1, 1, text);
   return View(items);
}

I’ve created a Search view which was auto-scaffolded based on the strongly typed model. The scaffolding is a nice feature and I can see this being extensible in the future.

Two things that I did get tripped up on for just a short while which required some trial and error was that I needed to create a new routing rule in global.asax to handle my Search action url format:

//Search Item
routes.MapRoute(
   "SearchItem",
   "{controller}/{action}/{text}",
   new { controller = "Item", action = "Search", text = UrlParameter.Optional }
);

I also discovered that _Layout.cshtml is essentially the masterpage (called a layout in MVC terms) and is auto-loaded by default from _ViewStart.cshtml.

That’s actually not a bad start for just opening up a project template and getting going, the wizard-style adding of files was very intuitive. Now it’s on to the resources to start learning more.

What Resources I’m Using This Week

Pluralsight: I’m finishing up the free MVC video on ASP.net and like the quality so much I’ve requested for our entire team to purchase seats through work. The catalog is certainly Microsoft-based but also has some “fringe” technology courses as well.

I’m not paid for any recommendation or traffic to Pluralsight, I just like their material.

HTML5 by Bruce Lawson and Remy Sharp: In line with using MVC, I think this is also an appropriate time to embrace HTML5 (as the rest of the world has gone crazy over it) as some of the HTML generated appears to be doctype’d for HTML5 in MVC as well now.

I did enroll in Amazon’s referral program, so there is a slight compensation for purchasing the book after clicking the image below.