5
votes

I have one (razor) page that contain 5 different partial views. Each partial view is responsible for some data from database. In that master page I use one model object but for partial views I use different model objects. The problem is that when I set model object in partial view my application breaks with following error: The model item passed into the dictionary is of type 'MyProject.WebUI.Models.BigPageViewModel', but this dictionary requires a model item of type 'MyProject.WebUI.Models.StatisticsViewModel'.

Here is the code: This is the big page that contains partial views:

@model MyProject.WebUI.Models.BigPageViewModel
@{
    Layout = "../Shared/_BigPage.cshtml";
}
...
@{Html.RenderPartial("../Data/StatisticsFeed");}
...

This is controller code. For this method I created partial view that should be rendered in big page.

public ActionResult StatisticsFeed()
        {
            StatisticsViewModel cs = new StatisticsViewModel();
            cs.TotalData = (new StatisticsRepository()).GetStatisticCompleteData(1);
            return View(cs);
        }

And this is the code in partial view:

@model MyProject.WebUI.Models.StatisticsViewModel
...

enter image description here

I used 'RenderAction' method instead of 'RenderPartial' and it return value but returns me two results one with data and one without, this must be some stupid mistake...

public ActionResult StatisticsFeed()
        {
          StatisticsViewModel cs = new StatisticsViewModel();
                cs.TotalData = (new StatisticsRepository()).GetStatisticCompleteData(1);

            cs.TotalCitizns = 569;
            return View(cs);
        }
1

1 Answers

8
votes

You need to specify explicitly the model being passed to the partial using the second argument of the RenderPartial method. If you don't specify it the parent model is passed and so the exception you get:

@{Html.RenderPartial("../Data/StatisticsFeed", Model.SomePropertyOfTypeStatisticsViewModel);}

Another possibility is to use RenderAction:

@{Html.RenderAction("StatisticsFeed", "ControllerName");}

This will invoke the StatisticsFeed controller action which itself will fetch the model from the database and render the results.