Search code examples
c#asp.net-mvcrazormodel-view-controllerrenderpartial

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?


Solution

  • 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