stormwild
stormwild

Reputation: 2955

How do I pass a model property to a partial view with a different model?

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?

Upvotes: 0

Views: 1078

Answers (2)

stormwild
stormwild

Reputation: 2955

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 });

Upvotes: 0

novian kristianto
novian kristianto

Reputation: 761

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

Upvotes: 1

Related Questions