The model item passed into the dictionary is of type… Not the usual reason

Working in MVC, I got an error that most working in MVC will eventually get:

The model item passed into the dictionary is of type Scooby, but this dictionary requires a model item of type Shaggy

 

No, this was not the usual case of my controller action returning one type, and my View expecting another type, like so:

// Controller
       public ActionResult ReturnScooby() {
           Scooby model = new Scooby();
           return View(model);
       }
// View
@model Cartoons.Models.Shaggy

 

My View and controller had matching types. In fact, there was nothing major going on, like those tricky partial views. Here is a pared-down view of my Scooby.cshtml View:

@model Cartoons.Models.Scooby
@{
   ViewBag.Title = "Hi Scooby";
}
@using (Html.BeginForm()) {
      @Html.LabelFor(m => m.Name)
      @Html.TextBoxFor(m => m.Name)
}

 

Seriously, not much more than that. Yet I was still getting the error. So I turned to the handy F11 key to step through and what I found was that the page was attempting to load a file called _ViewStart.cshtml:

@{
   Layout = "~/Views/Shared/_Layout.cshtml";
}

 

What? I didn’t tell it to load that. And I didn’t want it to load that, because _Layout.cshtml had an associated model of Daphne, and Daphne wasn’t invited to this party:

@model Cartoons.Models.Daphne
<!DOCTYPE html>

 

To stop Daphne from party crashing, I modified the Scooby.cshtml View, specifically telling it NOT to load the _ViewStart.cshtml file:

@model Cartoons.Models.Scooby
@{
   Layout = null;
}

 

That did the trick.

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: