0

Given a view model class

public class Foo 
{
   public string Fuzz { get; set; }
   public Bar Bar { get; set; }
}

public class Bar
{
   public string Fizz { get; set; }
}

In the controller action I pass the following model to the view:

View(new Foo { Fuzz = "Fizz", Bar = new Bar{ Fizz = "Fuzz" } });

In the view Foo.cshtml

@model Foo

@Model.Fuzz

@{ Html.RenderPartial("BarPartial", Model.Bar); }

In the view partial BarPartial.cshtml

@model Bar

@Model.Fizz

An error is thrown:

The model item passed into the dictionary is of type Foo but this dictionary requires a model item of type Bar.

How do I pass a property of the parent model to a partial view with a model that is a type of the property?

Christoph Fink
  • 22,727
  • 9
  • 68
  • 113
stormwild
  • 2,855
  • 2
  • 31
  • 38

2 Answers2

1
public ActionResult test2()
        {
            return View(new Foo { Fuzz = "Fizz", Bar = new Bar { Fizz = "Fuzz" } });
        }

my view

@model Foo

@Model.Fuzz
@{ Html.RenderPartial("_partial1",Model.Bar); }

my partial

@model Bar

@Model.Fizz

no different code, and work great for me

novian kristianto
  • 751
  • 3
  • 12
  • 34
0

I'm sorry I just figured out the error:

It seems in the real project I was working on the model I was passing was being set to null in later parts of the action code.

This error will occur:

The model item passed into the dictionary is of type Foo but this dictionary requires a model  item of type Bar.

if

View(new Foo { Fuzz = "Fizz", Bar = null });
stormwild
  • 2,855
  • 2
  • 31
  • 38