Search code examples
asp.net-mvc-3modelienumerablerenderpartial

MVC 3 Changing Model in Views with RenderPage


I'm having problems when trying to change the model of my view in MVC 3.

First view (index.cshtml) :

@model IEnumerable<MyProgram.MyFrogCollection>

<h1>Welcome to my frog collection</h1>
@foreach(MyProgram.Frog frog in Model)
{
  <div class="frogDetails">
    @RenderPage("ShowFrogDetails.cshtml", frog);
  </div>
}

Second view (ShowFrogDetails.cshtml), that I would like to use all over the site :

@model MyProgram.Frog

<h3>Name:</h3><div class="detail">@Model.Name</div>
<h3>Colour:</h3><div class="detail">@Model.Colour</div>

However when I try to run the page index.cshtml after passing in a list of frog objects I get the following error when getting to the @RenderPage line :

Server Error in '/' Application. The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[MyProgram.Frog]', but this dictionary requires a model item of type 'MyProgram.Frog'.

If I were to remove the code from ShowFrogDetails.cshtml and place it in-line within the foreach loop of index.cshtml the results are what I would expect. However this doesn't reuse existing code.

Is there anyway I can change the model to a single Frog object for use in the RenderPage ?

Cheers!


Solution

  • Try like this:

    <div class="frogDetails">
        @Html.Partial("ShowFrogDetails", frog)
    </div>