MVC 3 Changing a Model in Views Using RenderPage

I am having problems trying to change my view model 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> } 

The second view ( ShowFrogDetails.cshtml ) that I would like to use throughout 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 launch the index.cshtml page after passing to the list of frog objects, I get the following error when accessing the @RenderPage line:

Server error in application "/". The model element passed to the dictionary is of type 'System.Collections.Generic.List`1 [MyProgram.Frog]', but this dictionary requires a model element of type 'MyProgram.Frog'.

If I were to remove the code from ShowFrogDetails.cshtml and put it in a line inside the foreach index.cshtml loop, then I expect the results. However, this does not reuse existing code.

Anyway, can I change the model to a single Frog object for use in RenderPage?

Hurrah!

+6
source share
1 answer

Try it like this:

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

Source: https://habr.com/ru/post/898622/


All Articles